<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="AverageJoe&#39;s Blog">
    <meta name="description" content="this is my secret garden where I sow my inspirations.">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>AverageJoe&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
<meta name="generator" content="Hexo 5.0.0"><link rel="alternate" href="/atom.xml" title="AverageJoe's Blog" type="application/atom+xml">
</head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">AverageJoe&#39;s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>Contact</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>Friends</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">AverageJoe&#39;s Blog</div>
        <div class="logo-desc">
            
            this is my secret garden where I sow my inspirations.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			Contact
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			Friends
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/0.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title"></h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                          <div class="article-tag">
                            <span class="chip bg-color">No tag</span>
                          </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2018-10-11
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>Update Date:&nbsp;&nbsp;
                    2018-10-11
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    15.8k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>Read Times:&nbsp;&nbsp;
                    73 Min
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>Read Count:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="0-学习目标"><a href="#0-学习目标" class="headerlink" title="0.学习目标"></a>0.学习目标</h1><ul>
<li>独立安装Elasticsearch</li>
<li>会使用Rest的API操作索引</li>
<li>会使用Rest的API查询数据</li>
<li>会使用Rest的API聚合数据</li>
<li>掌握Spring Data Elasticsearch使用</li>
</ul>
<h1 id="1-Elasticsearch介绍和安装"><a href="#1-Elasticsearch介绍和安装" class="headerlink" title="1.Elasticsearch介绍和安装"></a>1.Elasticsearch介绍和安装</h1><p>用户访问我们的首页，一般都会直接搜索来寻找自己想要购买的商品。</p>
<p>而商品的数量非常多，而且分类繁杂。如果能正确的显示出用户想要的商品，并进行合理的过滤，尽快促成交易，是搜索系统要研究的核心。</p>
<p>面对这样复杂的搜索业务和数据量，使用传统数据库搜索就显得力不从心，一般我们都会使用全文检索技术，比如之前大家学习过的Solr。</p>
<p>不过今天，我们要讲的是另一个全文检索技术：Elasticsearch。</p>
<h2 id="1-1-简介"><a href="#1-1-简介" class="headerlink" title="1.1.简介"></a>1.1.简介</h2><h3 id="1-1-1-Elastic"><a href="#1-1-1-Elastic" class="headerlink" title="1.1.1.Elastic"></a>1.1.1.Elastic</h3><p>Elastic官网：<a target="_blank" rel="noopener" href="https://www.elastic.co/cn/">https://www.elastic.co/cn/</a></p>
<p><img src="assets/1528546351055.png" alt="1528546351055"></p>
<p>Elastic有一条完整的产品线及解决方案：Elasticsearch、Kibana、Logstash等，前面说的三个就是大家常说的ELK技术栈。</p>
<p><img src="assets/1528546493105.png" alt="1528546493105"></p>
<h3 id="1-1-2-Elasticsearch"><a href="#1-1-2-Elasticsearch" class="headerlink" title="1.1.2.Elasticsearch"></a>1.1.2.Elasticsearch</h3><p>Elasticsearch官网：<a target="_blank" rel="noopener" href="https://www.elastic.co/cn/products/elasticsearch">https://www.elastic.co/cn/products/elasticsearch</a></p>
<p><img src="assets/1528547087016.png" alt="1528547087016"></p>
<p>如上所述，Elasticsearch具备以下特点：</p>
<ul>
<li>分布式，无需人工搭建集群（solr就需要人为配置，使用Zookeeper作为注册中心）</li>
<li>Restful风格，一切API都遵循Rest原则，容易上手</li>
<li>近实时搜索，数据更新在Elasticsearch中几乎是完全同步的。</li>
</ul>
<h3 id="1-1-3-版本"><a href="#1-1-3-版本" class="headerlink" title="1.1.3.版本"></a>1.1.3.版本</h3><p>目前Elasticsearch最新的版本是6.3.1，我们就使用6.3.0</p>
<p><img src="assets/1528547283102.png" alt="1528547283102"></p>
<p>需要虚拟机JDK1.8及以上</p>
<h2 id="1-2-安装和配置"><a href="#1-2-安装和配置" class="headerlink" title="1.2.安装和配置"></a>1.2.安装和配置</h2><p>为了模拟真实场景，我们将在linux下安装Elasticsearch。</p>
<h3 id="1-2-1-新建一个用户leyou"><a href="#1-2-1-新建一个用户leyou" class="headerlink" title="1.2.1.新建一个用户leyou"></a>1.2.1.新建一个用户leyou</h3><p>出于安全考虑，elasticsearch默认不允许以root账号运行。</p>
<p>创建用户：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">useradd leyou</span><br></pre></td></tr></table></figure>

<p>设置密码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">passwd leyou</span><br></pre></td></tr></table></figure>

<p>切换用户：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">su - leyou</span><br></pre></td></tr></table></figure>



<h3 id="1-2-2-上传安装包-并解压"><a href="#1-2-2-上传安装包-并解压" class="headerlink" title="1.2.2.上传安装包,并解压"></a>1.2.2.上传安装包,并解压</h3><p>我们将安装包上传到：/home/leyou目录</p>
<p><img src="assets/1528610258461.png" alt="1528610258461"></p>
<p><img src="assets/1528551162835.png" alt="1528551162835"></p>
<p>解压缩：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tar -zxvf elasticsearch-6.2.4.tar.gz</span><br></pre></td></tr></table></figure>



<p>我们把目录重命名：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mv elasticsearch-6.2.4&#x2F; elasticsearch</span><br></pre></td></tr></table></figure>

<p><img src="assets/1528610397414.png" alt="1528610397414"></p>
<p>进入，查看目录结构：</p>
<p><img src="assets/1528551465373.png" alt="1528551465373"></p>
<h3 id="1-2-3-修改配置"><a href="#1-2-3-修改配置" class="headerlink" title="1.2.3.修改配置"></a>1.2.3.修改配置</h3><p>我们进入config目录：<code>cd config</code></p>
<p>需要修改的配置文件有两个：</p>
<p><img src="assets/1528551598931.png" alt="1528551598931"></p>
<ol>
<li><strong>jvm.options</strong></li>
</ol>
<p>Elasticsearch基于Lucene的，而Lucene底层是java实现，因此我们需要配置jvm参数。</p>
<p>编辑jvm.options：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vim jvm.options</span><br></pre></td></tr></table></figure>

<p>默认配置如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">-Xms1g</span><br><span class="line">-Xmx1g</span><br></pre></td></tr></table></figure>

<p>内存占用太多了，我们调小一些：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">-Xms512m</span><br><span class="line">-Xmx512m</span><br></pre></td></tr></table></figure>

<ol>
<li><strong>elasticsearch.yml</strong></li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vim elasticsearch.yml</span><br></pre></td></tr></table></figure>

<ul>
<li>修改数据和日志目录：</li>
</ul>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">path.data:</span> <span class="string">/home/leyou/elasticsearch/data</span> <span class="comment"># 数据目录位置</span></span><br><span class="line"><span class="attr">path.logs:</span> <span class="string">/home/leyou/elasticsearch/logs</span> <span class="comment"># 日志目录位置</span></span><br></pre></td></tr></table></figure>

<p>我们把data和logs目录修改指向了elasticsearch的安装目录。但是这两个目录并不存在，因此我们需要创建出来。</p>
<p>进入elasticsearch的根目录，然后创建：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mkdir data</span><br><span class="line">mkdir logs</span><br></pre></td></tr></table></figure>

<p><img src="assets/1528552839032.png" alt="1528552839032"></p>
<ul>
<li>修改绑定的ip：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">network.host: 0.0.0.0 # 绑定到0.0.0.0，允许任何ip来访问</span><br></pre></td></tr></table></figure>

<p>默认只允许本机访问，修改为0.0.0.0后则可以远程访问</p>
<p>目前我们是做的单机安装，如果要做集群，只需要在这个配置文件中添加其它节点信息即可。</p>
<blockquote>
<p>elasticsearch.yml的其它可配置信息：</p>
</blockquote>
<table>
<thead>
<tr>
<th>属性名</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>cluster.name</td>
<td>配置elasticsearch的集群名称，默认是elasticsearch。建议修改成一个有意义的名称。</td>
</tr>
<tr>
<td>node.name</td>
<td>节点名，es会默认随机指定一个名字，建议指定一个有意义的名称，方便管理</td>
</tr>
<tr>
<td>path.conf</td>
<td>设置配置文件的存储路径，tar或zip包安装默认在es根目录下的config文件夹，rpm安装默认在/etc/ elasticsearch</td>
</tr>
<tr>
<td>path.data</td>
<td>设置索引数据的存储路径，默认是es根目录下的data文件夹，可以设置多个存储路径，用逗号隔开</td>
</tr>
<tr>
<td>path.logs</td>
<td>设置日志文件的存储路径，默认是es根目录下的logs文件夹</td>
</tr>
<tr>
<td>path.plugins</td>
<td>设置插件的存放路径，默认是es根目录下的plugins文件夹</td>
</tr>
<tr>
<td>bootstrap.memory_lock</td>
<td>设置为true可以锁住ES使用的内存，避免内存进行swap</td>
</tr>
<tr>
<td>network.host</td>
<td>设置bind_host和publish_host，设置为0.0.0.0允许外网访问</td>
</tr>
<tr>
<td>http.port</td>
<td>设置对外服务的http端口，默认为9200。</td>
</tr>
<tr>
<td>transport.tcp.port</td>
<td>集群结点之间通信端口</td>
</tr>
<tr>
<td>discovery.zen.ping.timeout</td>
<td>设置ES自动发现节点连接超时的时间，默认为3秒，如果网络延迟高可设置大些</td>
</tr>
<tr>
<td>discovery.zen.minimum_master_nodes</td>
<td>主结点数量的最少值 ,此值的公式为：(master_eligible_nodes / 2) + 1 ，比如：有3个符合要求的主结点，那么这里要设置为2</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody></table>
<h2 id="1-3-运行"><a href="#1-3-运行" class="headerlink" title="1.3.运行"></a>1.3.运行</h2><p>进入elasticsearch/bin目录，可以看到下面的执行文件：</p>
<p><img src="assets/1528553103468.png" alt="1528553103468"></p>
<p>然后输入命令：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">.&#x2F;elasticsearch</span><br></pre></td></tr></table></figure>

<p>发现报错了，启动失败：</p>
<h3 id="1-3-1-错误1：内核过低"><a href="#1-3-1-错误1：内核过低" class="headerlink" title="1.3.1.错误1：内核过低"></a>1.3.1.错误1：内核过低</h3><p><img src="assets/1528598315714.png" alt="1528598315714"></p>
<p>我们使用的是centos6，其linux内核版本为2.6。而Elasticsearch的插件要求至少3.5以上版本。不过没关系，我们禁用这个插件即可。</p>
<p>修改elasticsearch.yml文件，在最下面添加如下配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">bootstrap.system_call_filter: false</span><br></pre></td></tr></table></figure>

<p>然后重启</p>
<h3 id="1-3-2-错误2：文件权限不足"><a href="#1-3-2-错误2：文件权限不足" class="headerlink" title="1.3.2.错误2：文件权限不足"></a>1.3.2.错误2：文件权限不足</h3><p>再次启动，又出错了：</p>
<p><img src="assets/1528599116836.png" alt="1528599116836"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[1]: max file descriptors [4096] for elasticsearch process likely too low, increase to at least [65536]</span><br></pre></td></tr></table></figure>

<p>我们用的是leyou用户，而不是root，所以文件权限不足。</p>
<p><strong>首先用root用户登录。</strong></p>
<p>然后修改配置文件:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vim &#x2F;etc&#x2F;security&#x2F;limits.conf</span><br></pre></td></tr></table></figure>

<p>添加下面的内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">* soft nofile 65536</span><br><span class="line"></span><br><span class="line">* hard nofile 131072</span><br><span class="line"></span><br><span class="line">* soft nproc 4096</span><br><span class="line"></span><br><span class="line">* hard nproc 4096</span><br></pre></td></tr></table></figure>



<h3 id="1-3-3-错误3：线程数不够"><a href="#1-3-3-错误3：线程数不够" class="headerlink" title="1.3.3.错误3：线程数不够"></a>1.3.3.错误3：线程数不够</h3><p>刚才报错中，还有一行：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[1]: max number of threads [1024] for user [leyou] is too low, increase to at least [4096]</span><br></pre></td></tr></table></figure>

<p>这是线程数不够。</p>
<p>继续修改配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vim &#x2F;etc&#x2F;security&#x2F;limits.d&#x2F;90-nproc.conf </span><br></pre></td></tr></table></figure>

<p>修改下面的内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">* soft nproc 1024</span><br></pre></td></tr></table></figure>

<p>改为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">* soft nproc 4096</span><br></pre></td></tr></table></figure>



<h3 id="1-3-4-错误4：进程虚拟内存"><a href="#1-3-4-错误4：进程虚拟内存" class="headerlink" title="1.3.4.错误4：进程虚拟内存"></a>1.3.4.错误4：进程虚拟内存</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[3]: max virtual memory areas vm.max_map_count [65530] likely too low, increase to at least [262144]</span><br></pre></td></tr></table></figure>

<p>vm.max_map_count：限制一个进程可以拥有的VMA(虚拟内存区域)的数量，继续修改配置文件， ：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vim &#x2F;etc&#x2F;sysctl.conf </span><br></pre></td></tr></table></figure>

<p>添加下面内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vm.max_map_count&#x3D;655360</span><br></pre></td></tr></table></figure>

<p>然后执行命令：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sysctl -p</span><br></pre></td></tr></table></figure>



<h3 id="1-3-5-重启终端窗口"><a href="#1-3-5-重启终端窗口" class="headerlink" title="1.3.5.重启终端窗口"></a>1.3.5.重启终端窗口</h3><p>所有错误修改完毕，一定要重启你的 Xshell终端，否则配置无效。</p>
<h3 id="1-3-6-启动"><a href="#1-3-6-启动" class="headerlink" title="1.3.6.启动"></a>1.3.6.启动</h3><p>再次启动，终于成功了！</p>
<p><img src="assets/1528603044862.png" alt="1528603044862"></p>
<p>可以看到绑定了两个端口:</p>
<ul>
<li>9300：集群节点间通讯接口</li>
<li>9200：客户端访问接口</li>
</ul>
<p>我们在浏览器中访问：<a target="_blank" rel="noopener" href="http://192.168.56.101:9200/">http://192.168.56.101:9200</a></p>
<p><img src="assets/1528611090621.png" alt="1528611090621"></p>
<h2 id="1-4-安装kibana"><a href="#1-4-安装kibana" class="headerlink" title="1.4.安装kibana"></a>1.4.安装kibana</h2><h3 id="1-4-1-什么是Kibana？"><a href="#1-4-1-什么是Kibana？" class="headerlink" title="1.4.1.什么是Kibana？"></a>1.4.1.什么是Kibana？</h3><p><img src="assets/1528603530298.png" alt="1528603530298"></p>
<p>Kibana是一个基于Node.js的Elasticsearch索引库数据统计工具，可以利用Elasticsearch的聚合功能，生成各种图表，如柱形图，线状图，饼图等。</p>
<p>而且还提供了操作Elasticsearch索引数据的控制台，并且提供了一定的API提示，非常有利于我们学习Elasticsearch的语法。</p>
<h3 id="1-4-2-安装"><a href="#1-4-2-安装" class="headerlink" title="1.4.2.安装"></a>1.4.2.安装</h3><p>因为Kibana依赖于node，我们的虚拟机没有安装node，而window中安装过。所以我们选择在window下使用kibana。</p>
<p>最新版本与elasticsearch保持一致，也是6.3.0</p>
<p><img src="assets/1528611218599.png" alt="1528611218599"></p>
<p>解压到特定目录即可</p>
<h3 id="1-4-3-配置运行"><a href="#1-4-3-配置运行" class="headerlink" title="1.4.3.配置运行"></a>1.4.3.配置运行</h3><blockquote>
<p>配置</p>
</blockquote>
<p>进入安装目录下的config目录，修改kibana.yml文件：</p>
<p>修改elasticsearch服务器的地址：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">elasticsearch.url: &quot;http:&#x2F;&#x2F;192.168.56.101:9200&quot;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>运行</p>
</blockquote>
<p>进入安装目录下的bin目录：</p>
<p><img src="assets/1528612108406.png" alt="1528612108406"></p>
<p>双击运行：</p>
<p><img src="assets/1528612216033.png" alt="1528612216033"></p>
<p>发现kibana的监听端口是5601</p>
<p>我们访问：<a target="_blank" rel="noopener" href="http://127.0.0.1:5601/">http://127.0.0.1:5601</a></p>
<p><img src="assets/1528612265677.png" alt="1528612265677"></p>
<h3 id="1-4-4-控制台"><a href="#1-4-4-控制台" class="headerlink" title="1.4.4.控制台"></a>1.4.4.控制台</h3><p>选择左侧的DevTools菜单，即可进入控制台页面：</p>
<p><img src="assets/1528612350020.png" alt="1528612350020"></p>
<p>在页面右侧，我们就可以输入请求，访问Elasticsearch了。</p>
<p><img src="assets/1528612514556.png" alt="1528612514556"></p>
<h2 id="1-5-安装ik分词器"><a href="#1-5-安装ik分词器" class="headerlink" title="1.5.安装ik分词器"></a>1.5.安装ik分词器</h2><p>Lucene的IK分词器早在2012年已经没有维护了，现在我们要使用的是在其基础上维护升级的版本，并且开发为ElasticSearch的集成插件了，与Elasticsearch一起维护升级，版本也保持一致，最新版本：6.3.0</p>
<h3 id="1-5-1-安装"><a href="#1-5-1-安装" class="headerlink" title="1.5.1.安装"></a>1.5.1.安装</h3><p>上传课前资料中的zip包，解压到Elasticsearch目录的plugins目录中：</p>
<p><img src="assets/1528612654570.png" alt="1526482432181"></p>
<p>使用unzip命令解压：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">unzip elasticsearch-analysis-ik-6.3.0.zip -d ik-analyzer</span><br></pre></td></tr></table></figure>

<p>然后重启elasticsearch：</p>
<p><img src="assets/1528612928524.png" alt="1528612928524"></p>
<h3 id="1-5-2-测试"><a href="#1-5-2-测试" class="headerlink" title="1.5.2.测试"></a>1.5.2.测试</h3><p>大家先不管语法，我们先测试一波。</p>
<p>在kibana控制台输入下面的请求：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">POST _analyze</span><br><span class="line">&#123;</span><br><span class="line">  &quot;analyzer&quot;: &quot;ik_max_word&quot;,</span><br><span class="line">  &quot;text&quot;:     &quot;我是中国人&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行得到结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  &quot;tokens&quot;: [</span><br><span class="line">    &#123;</span><br><span class="line">      &quot;token&quot;: &quot;我&quot;,</span><br><span class="line">      &quot;start_offset&quot;: 0,</span><br><span class="line">      &quot;end_offset&quot;: 1,</span><br><span class="line">      &quot;type&quot;: &quot;CN_CHAR&quot;,</span><br><span class="line">      &quot;position&quot;: 0</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      &quot;token&quot;: &quot;是&quot;,</span><br><span class="line">      &quot;start_offset&quot;: 1,</span><br><span class="line">      &quot;end_offset&quot;: 2,</span><br><span class="line">      &quot;type&quot;: &quot;CN_CHAR&quot;,</span><br><span class="line">      &quot;position&quot;: 1</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      &quot;token&quot;: &quot;中国人&quot;,</span><br><span class="line">      &quot;start_offset&quot;: 2,</span><br><span class="line">      &quot;end_offset&quot;: 5,</span><br><span class="line">      &quot;type&quot;: &quot;CN_WORD&quot;,</span><br><span class="line">      &quot;position&quot;: 2</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      &quot;token&quot;: &quot;中国&quot;,</span><br><span class="line">      &quot;start_offset&quot;: 2,</span><br><span class="line">      &quot;end_offset&quot;: 4,</span><br><span class="line">      &quot;type&quot;: &quot;CN_WORD&quot;,</span><br><span class="line">      &quot;position&quot;: 3</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      &quot;token&quot;: &quot;国人&quot;,</span><br><span class="line">      &quot;start_offset&quot;: 3,</span><br><span class="line">      &quot;end_offset&quot;: 5,</span><br><span class="line">      &quot;type&quot;: &quot;CN_WORD&quot;,</span><br><span class="line">      &quot;position&quot;: 4</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="1-7-API"><a href="#1-7-API" class="headerlink" title="1.7.API"></a>1.7.API</h2><p>Elasticsearch提供了Rest风格的API，即http请求接口，而且也提供了各种语言的客户端API</p>
<h3 id="1-7-1-Rest风格API"><a href="#1-7-1-Rest风格API" class="headerlink" title="1.7.1.Rest风格API"></a>1.7.1.Rest风格API</h3><p>文档地址：<a target="_blank" rel="noopener" href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html">https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html</a></p>
<p><img src="H:/%E4%B9%90%E4%BC%98/7%E6%9C%881%E5%8F%B7%E6%9B%B4%E6%96%B0/day11-elasticsearch/assets/1526518410240.png" alt="1526518410240"></p>
<h3 id="1-7-2-客户端API"><a href="#1-7-2-客户端API" class="headerlink" title="1.7.2.客户端API"></a>1.7.2.客户端API</h3><p>Elasticsearch支持的客户端非常多：<a target="_blank" rel="noopener" href="https://www.elastic.co/guide/en/elasticsearch/client/index.html">https://www.elastic.co/guide/en/elasticsearch/client/index.html</a></p>
<p><img src="assets/1528613714338.png" alt="1528613714338"></p>
<p>点击Java Rest Client后，你会发现又有两个：</p>
<p><img src="assets/1528613788606.png" alt="1528613788606"></p>
<p>Low Level Rest Client是低级别封装，提供一些基础功能，但更灵活</p>
<p>High Level Rest Client，是在Low  Level Rest Client基础上进行的高级别封装，功能更丰富和完善，而且API会变的简单</p>
<p> <img src="assets/1526518875072.png" alt="1526518875072"></p>
<h3 id="1-7-3-如何学习"><a href="#1-7-3-如何学习" class="headerlink" title="1.7.3.如何学习"></a>1.7.3.如何学习</h3><p>建议先学习Rest风格API，了解发起请求的底层实现，请求体格式等。</p>
<h1 id="2-操作索引"><a href="#2-操作索引" class="headerlink" title="2.操作索引"></a>2.操作索引</h1><h2 id="2-1-基本概念"><a href="#2-1-基本概念" class="headerlink" title="2.1.基本概念"></a>2.1.基本概念</h2><p>Elasticsearch也是基于Lucene的全文检索库，本质也是存储数据，很多概念与MySQL类似的。</p>
<p>对比关系：</p>
<p>索引（indices）——————————–Databases 数据库</p>
<p>​    类型（type）—————————–Table 数据表</p>
<p>​         文档（Document）—————-Row 行</p>
<p>​           字段（Field）——————-Columns 列 </p>
<p>详细说明：</p>
<table>
<thead>
<tr>
<th>概念</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>索引库（indices)</td>
<td>indices是index的复数，代表许多的索引，</td>
</tr>
<tr>
<td>类型（type）</td>
<td>类型是模拟mysql中的table概念，一个索引库下可以有不同类型的索引，比如商品索引，订单索引，其数据格式不同。不过这会导致索引库混乱，因此未来版本中会移除这个概念</td>
</tr>
<tr>
<td>文档（document）</td>
<td>存入索引库原始的数据。比如每一条商品信息，就是一个文档</td>
</tr>
<tr>
<td>字段（field）</td>
<td>文档中的属性</td>
</tr>
<tr>
<td>映射配置（mappings）</td>
<td>字段的数据类型、属性、是否索引、是否存储等特性</td>
</tr>
</tbody></table>
<p>是不是与Lucene和solr中的概念类似。</p>
<p>另外，在SolrCloud中，有一些集群相关的概念，在Elasticsearch也有类似的：</p>
<ul>
<li>索引集（Indices，index的复数）：逻辑上的完整索引</li>
<li>分片（shard）：数据拆分后的各个部分</li>
<li>副本（replica）：每个分片的复制</li>
</ul>
<p>要注意的是：Elasticsearch本身就是分布式的，因此即便你只有一个节点，Elasticsearch默认也会对你的数据进行分片和副本操作，当你向集群添加新数据时，数据也会在新加入的节点中进行平衡。</p>
<h2 id="2-2-创建索引"><a href="#2-2-创建索引" class="headerlink" title="2.2.创建索引"></a>2.2.创建索引</h2><h3 id="2-2-1-语法"><a href="#2-2-1-语法" class="headerlink" title="2.2.1.语法"></a>2.2.1.语法</h3><p>Elasticsearch采用Rest风格API，因此其API就是一次http请求，你可以用任何工具发起http请求</p>
<p>创建索引的请求格式：</p>
<ul>
<li><p>请求方式：PUT</p>
</li>
<li><p>请求路径：/索引库名</p>
</li>
<li><p>请求参数：json格式：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;settings&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;number_of_shards&quot;</span>: <span class="number">3</span>,</span><br><span class="line">        <span class="attr">&quot;number_of_replicas&quot;</span>: <span class="number">2</span></span><br><span class="line">      &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>settings：索引库的设置<ul>
<li>number_of_shards：分片数量</li>
<li>number_of_replicas：副本数量</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="2-2-2-测试"><a href="#2-2-2-测试" class="headerlink" title="2.2.2.测试"></a>2.2.2.测试</h3><p>我们先用RestClient来试试</p>
<p><img src="assets/1528615921930.png" alt="1528615921930"></p>
<p>响应：</p>
<p><img src="assets/1528615945473.png" alt="1528615945473"></p>
<p>可以看到索引创建成功了。</p>
<h3 id="2-2-3-使用kibana创建"><a href="#2-2-3-使用kibana创建" class="headerlink" title="2.2.3.使用kibana创建"></a>2.2.3.使用kibana创建</h3><p>kibana的控制台，可以对http请求进行简化，示例：</p>
<p><img src="assets/1528616088691.png" alt="1528616088691"></p>
<p>相当于是省去了elasticsearch的服务器地址</p>
<p>而且还有语法提示，非常舒服。</p>
<h2 id="2-3-查看索引设置"><a href="#2-3-查看索引设置" class="headerlink" title="2.3.查看索引设置"></a>2.3.查看索引设置</h2><blockquote>
<p>语法</p>
</blockquote>
<p>Get请求可以帮我们查看索引信息，格式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GET &#x2F;索引库名</span><br></pre></td></tr></table></figure>

<p><img src="assets/1528616233409.png" alt="1528616233409"></p>
<p>或者，我们可以使用*来查询所有索引库配置：</p>
<p><img src="assets/1528616305800.png" alt="1528616305800"></p>
<h2 id="2-4-删除索引"><a href="#2-4-删除索引" class="headerlink" title="2.4.删除索引"></a>2.4.删除索引</h2><p>删除索引使用DELETE请求</p>
<blockquote>
<p>语法</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DELETE &#x2F;索引库名</span><br></pre></td></tr></table></figure>

<blockquote>
<p>示例</p>
</blockquote>
<p><img src="assets/1528616383952.png" alt="1528616383952"></p>
<p>再次查看heima2：</p>
<p><img src="assets/1528616452713.png" alt="1528616452713"></p>
<p>当然，我们也可以用HEAD请求，查看索引是否存在：</p>
<p><img src="assets/1528616489638.png" alt="1528616489638"></p>
<h2 id="2-5-映射配置"><a href="#2-5-映射配置" class="headerlink" title="2.5.映射配置"></a>2.5.映射配置</h2><p>索引有了，接下来肯定是添加数据。但是，在添加数据之前必须定义映射。</p>
<p>什么是映射？</p>
<p>​    映射是定义文档的过程，文档包含哪些字段，这些字段是否保存，是否索引，是否分词等</p>
<p>只有配置清楚，Elasticsearch才会帮我们进行索引库的创建（不一定）</p>
<h3 id="2-5-1-创建映射字段"><a href="#2-5-1-创建映射字段" class="headerlink" title="2.5.1.创建映射字段"></a>2.5.1.创建映射字段</h3><blockquote>
<p>语法</p>
</blockquote>
<p>请求方式依然是PUT</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">PUT &#x2F;索引库名&#x2F;_mapping&#x2F;类型名称</span><br><span class="line">&#123;</span><br><span class="line">  &quot;properties&quot;: &#123;</span><br><span class="line">    &quot;字段名&quot;: &#123;</span><br><span class="line">      &quot;type&quot;: &quot;类型&quot;,</span><br><span class="line">      &quot;index&quot;: true，</span><br><span class="line">      &quot;store&quot;: true，</span><br><span class="line">      &quot;analyzer&quot;: &quot;分词器&quot;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>类型名称：就是前面将的type的概念，类似于数据库中的不同表<br>字段名：任意填写    ，可以指定许多属性，例如：</li>
<li>type：类型，可以是text、long、short、date、integer、object等</li>
<li>index：是否索引，默认为true</li>
<li>store：是否存储，默认为false</li>
<li>analyzer：分词器，这里的<code>ik_max_word</code>即使用ik分词器</li>
</ul>
<blockquote>
<p>示例</p>
</blockquote>
<p>发起请求：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">PUT heima/_mapping/goods</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;properties&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;text&quot;</span>,</span><br><span class="line">      <span class="attr">&quot;analyzer&quot;</span>: <span class="string">&quot;ik_max_word&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;keyword&quot;</span>,</span><br><span class="line">      <span class="attr">&quot;index&quot;</span>: <span class="string">&quot;false&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;float&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>响应结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  &quot;acknowledged&quot;: true</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h3 id="2-5-2-查看映射关系"><a href="#2-5-2-查看映射关系" class="headerlink" title="2.5.2.查看映射关系"></a>2.5.2.查看映射关系</h3><blockquote>
<p>语法：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GET &#x2F;索引库名&#x2F;_mapping</span><br></pre></td></tr></table></figure>

<blockquote>
<p>示例：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GET &#x2F;heima&#x2F;_mapping</span><br></pre></td></tr></table></figure>

<blockquote>
<p>响应：</p>
</blockquote>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;heima&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;mappings&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;goods&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;properties&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;keyword&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;index&quot;</span>: <span class="literal">false</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;float&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;text&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;analyzer&quot;</span>: <span class="string">&quot;ik_max_word&quot;</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="2-5-3-字段属性详解"><a href="#2-5-3-字段属性详解" class="headerlink" title="2.5.3.字段属性详解"></a>2.5.3.字段属性详解</h3><h4 id="2-5-3-1-type"><a href="#2-5-3-1-type" class="headerlink" title="2.5.3.1.type"></a>2.5.3.1.type</h4><p>Elasticsearch中支持的数据类型非常丰富：</p>
<p><img src="assets/1531712631982.png" alt="1531712631982"></p>
<p>我们说几个关键的：</p>
<ul>
<li><p>String类型，又分两种：</p>
<ul>
<li>text：可分词，不可参与聚合</li>
<li>keyword：不可分词，数据会作为完整字段进行匹配，可以参与聚合</li>
</ul>
</li>
<li><p>Numerical：数值类型，分两类</p>
<ul>
<li>基本数据类型：long、interger、short、byte、double、float、half_float</li>
<li>浮点数的高精度类型：scaled_float<ul>
<li>需要指定一个精度因子，比如10或100。elasticsearch会把真实值乘以这个因子后存储，取出时再还原。</li>
</ul>
</li>
</ul>
</li>
<li><p>Date：日期类型</p>
<p>elasticsearch可以对日期格式化为字符串存储，但是建议我们存储为毫秒值，存储为long，节省空间。</p>
</li>
</ul>
<h4 id="2-5-3-2-index"><a href="#2-5-3-2-index" class="headerlink" title="2.5.3.2.index"></a>2.5.3.2.index</h4><p>index影响字段的索引情况。</p>
<ul>
<li>true：字段会被索引，则可以用来进行搜索。默认值就是true</li>
<li>false：字段不会被索引，不能用来搜索</li>
</ul>
<p>index的默认值就是true，也就是说你不进行任何配置，所有字段都会被索引。</p>
<p>但是有些字段是我们不希望被索引的，比如商品的图片信息，就需要手动设置index为false。</p>
<h4 id="2-5-3-3-store"><a href="#2-5-3-3-store" class="headerlink" title="2.5.3.3.store"></a>2.5.3.3.store</h4><p>是否将数据进行额外存储。</p>
<p>在学习lucene和solr时，我们知道如果一个字段的store设置为false，那么在文档列表中就不会有这个字段的值，用户的搜索结果中不会显示出来。</p>
<p>但是在Elasticsearch中，即便store设置为false，也可以搜索到结果。</p>
<p>原因是Elasticsearch在创建文档索引时，会将文档中的原始数据备份，保存到一个叫做<code>_source</code>的属性中。而且我们可以通过过滤<code>_source</code>来选择哪些要显示，哪些不显示。</p>
<p>而如果设置store为true，就会在<code>_source</code>以外额外存储一份数据，多余，因此一般我们都会将store设置为false，事实上，<strong>store的默认值就是false。</strong></p>
<h4 id="2-5-3-4-boost"><a href="#2-5-3-4-boost" class="headerlink" title="2.5.3.4.boost"></a>2.5.3.4.boost</h4><p>激励因子，这个与lucene中一样</p>
<p>其它的不再一一讲解，用的不多，大家参考官方文档：</p>
<p><img src="assets/1531713176079.png" alt="1531713176079"></p>
<h2 id="2-6-新增数据"><a href="#2-6-新增数据" class="headerlink" title="2.6.新增数据"></a>2.6.新增数据</h2><h3 id="2-6-1-随机生成id"><a href="#2-6-1-随机生成id" class="headerlink" title="2.6.1.随机生成id"></a>2.6.1.随机生成id</h3><p>通过POST请求，可以向一个已经存在的索引库中添加数据。</p>
<blockquote>
<p>语法：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">POST &#x2F;索引库名&#x2F;类型名</span><br><span class="line">&#123;</span><br><span class="line">    &quot;key&quot;:&quot;value&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>示例：</p>
</blockquote>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">POST /heima/goods/</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>:<span class="string">&quot;小米手机&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>:<span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>:<span class="number">2699.00</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>响应：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;r9c1KGMBIhaxtY5rlRKv&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_version&quot;</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">&quot;result&quot;</span>: <span class="string">&quot;created&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;_seq_no&quot;</span>: <span class="number">0</span>,</span><br><span class="line">  <span class="attr">&quot;_primary_term&quot;</span>: <span class="number">2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>通过kibana查看数据：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">get _search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="string">&quot;match_all&quot;</span>:&#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;r9c1KGMBIhaxtY5rlRKv&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_version&quot;</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>: <span class="number">2699</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><code>_source</code>：源文档信息，所有的数据都在里面。</li>
<li><code>_id</code>：这条文档的唯一标示，与文档自己的id字段没有关联</li>
</ul>
<h3 id="2-6-2-自定义id"><a href="#2-6-2-自定义id" class="headerlink" title="2.6.2.自定义id"></a>2.6.2.自定义id</h3><p>如果我们想要自己新增的时候指定id，可以这么做：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">POST &#x2F;索引库名&#x2F;类型&#x2F;id值</span><br><span class="line">&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>示例：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">POST /heima/goods/2</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>:<span class="string">&quot;大米手机&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>:<span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>:<span class="number">2899.00</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>得到的数据：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;2&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;大米手机&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>: <span class="number">2899</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="2-6-3-智能判断"><a href="#2-6-3-智能判断" class="headerlink" title="2.6.3.智能判断"></a>2.6.3.智能判断</h3><p>在学习Solr时我们发现，我们在新增数据时，只能使用提前配置好映射属性的字段，否则就会报错。</p>
<p>不过在Elasticsearch中并没有这样的规定。</p>
<p>事实上Elasticsearch非常智能，你不需要给索引库设置任何mapping映射，它也可以根据你输入的数据来判断类型，动态添加数据映射。</p>
<p>测试一下：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">POST /heima/goods/3</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>:<span class="string">&quot;超米手机&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>:<span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>:<span class="number">2899.00</span>,</span><br><span class="line">    <span class="attr">&quot;stock&quot;</span>: <span class="number">200</span>,</span><br><span class="line">    <span class="attr">&quot;saleable&quot;</span>:<span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们额外添加了stock库存，和saleable是否上架两个字段。</p>
<p>来看结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;3&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;_version&quot;</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;超米手机&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>: <span class="number">2899</span>,</span><br><span class="line">    <span class="attr">&quot;stock&quot;</span>: <span class="number">200</span>,</span><br><span class="line">    <span class="attr">&quot;saleable&quot;</span>: <span class="literal">true</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在看下索引库的映射关系:</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;heima&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;mappings&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;goods&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;properties&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;keyword&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;index&quot;</span>: <span class="literal">false</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;float&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;saleable&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;boolean&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;stock&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;long&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;text&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;analyzer&quot;</span>: <span class="string">&quot;ik_max_word&quot;</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>stock和saleable都被成功映射了。</p>
<h2 id="2-7-修改数据"><a href="#2-7-修改数据" class="headerlink" title="2.7.修改数据"></a>2.7.修改数据</h2><p>把刚才新增的请求方式改为PUT，就是修改了。不过修改必须指定id，</p>
<ul>
<li>id对应文档存在，则修改</li>
<li>id对应文档不存在，则新增</li>
</ul>
<p>比如，我们把id为3的数据进行修改：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">PUT /heima/goods/3</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>:<span class="string">&quot;超大米手机&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>:<span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>:<span class="number">3899.00</span>,</span><br><span class="line">    <span class="attr">&quot;stock&quot;</span>: <span class="number">100</span>,</span><br><span class="line">    <span class="attr">&quot;saleable&quot;</span>:<span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">17</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">9</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">9</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;3&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;超大米手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">3899</span>,</span><br><span class="line">          <span class="attr">&quot;stock&quot;</span>: <span class="number">100</span>,</span><br><span class="line">          <span class="attr">&quot;saleable&quot;</span>: <span class="literal">true</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="2-8-删除数据"><a href="#2-8-删除数据" class="headerlink" title="2.8.删除数据"></a>2.8.删除数据</h2><p>删除使用DELETE请求，同样，需要根据id进行删除：</p>
<blockquote>
<p>语法</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DELETE &#x2F;索引库名&#x2F;类型名&#x2F;id值</span><br></pre></td></tr></table></figure>

<blockquote>
<p>示例：</p>
</blockquote>
<p><img src="assets/1531727693743.png" alt="1531727693743"></p>
<h1 id="3-查询"><a href="#3-查询" class="headerlink" title="3.查询"></a>3.查询</h1><p>我们从4块来讲查询：</p>
<ul>
<li>基本查询</li>
<li><code>_source</code>过滤</li>
<li>结果过滤</li>
<li>高级查询</li>
<li>排序</li>
</ul>
<h2 id="3-1-基本查询："><a href="#3-1-基本查询：" class="headerlink" title="3.1.基本查询："></a>3.1.基本查询：</h2><blockquote>
<p>基本语法</p>
</blockquote>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">GET /索引库名/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;查询类型&quot;</span>:&#123;</span><br><span class="line">            <span class="attr">&quot;查询条件&quot;</span>:<span class="string">&quot;查询条件值&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里的query代表一个查询对象，里面可以有不同的查询属性</p>
<ul>
<li>查询类型：<ul>
<li>例如：<code>match_all</code>， <code>match</code>，<code>term</code> ， <code>range</code> 等等</li>
</ul>
</li>
<li>查询条件：查询条件会根据类型的不同，写法也有差异，后面详细讲解</li>
</ul>
<h3 id="3-1-1-查询所有（match-all"><a href="#3-1-1-查询所有（match-all" class="headerlink" title="3.1.1 查询所有（match_all)"></a>3.1.1 查询所有（match_all)</h3><blockquote>
<p>示例：</p>
</blockquote>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;match_all&quot;</span>: &#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><code>query</code>：代表查询对象</li>
<li><code>match_all</code>：代表查询所有</li>
</ul>
<blockquote>
<p>结果：</p>
</blockquote>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">2</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">2</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;2&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;大米手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">2899</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;r9c1KGMBIhaxtY5rlRKv&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">2699</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>took：查询花费时间，单位是毫秒</li>
<li>time_out：是否超时</li>
<li>_shards：分片信息</li>
<li>hits：搜索结果总览对象<ul>
<li>total：搜索到的总条数</li>
<li>max_score：所有结果中文档得分的最高分</li>
<li>hits：搜索结果的文档对象数组，每个元素是一条搜索到的文档信息<ul>
<li>_index：索引库</li>
<li>_type：文档类型</li>
<li>_id：文档id</li>
<li>_score：文档得分</li>
<li>_source：文档的源数据</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="3-1-2-匹配查询（match）"><a href="#3-1-2-匹配查询（match）" class="headerlink" title="3.1.2 匹配查询（match）"></a>3.1.2 匹配查询（match）</h3><p>我们先加入一条数据，便于测试：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">PUT /heima/goods/3</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>:<span class="string">&quot;小米电视4A&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>:<span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>:<span class="number">3899.00</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在，索引库中有2部手机，1台电视：</p>
<p> <img src="assets/1531728628406.png" alt="1531728628406"></p>
<ul>
<li>or关系</li>
</ul>
<p><code>match</code>类型查询，会把查询条件进行分词，然后进行查询,多个词条之间是or的关系</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;match&quot;</span>:&#123;</span><br><span class="line">            <span class="attr">&quot;title&quot;</span>:<span class="string">&quot;小米电视&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">&quot;hits&quot;: &#123;</span><br><span class="line">    &quot;total&quot;: 2,</span><br><span class="line">    &quot;max_score&quot;: 0.6931472,</span><br><span class="line">    &quot;hits&quot;: [</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;tmUBomQB_mwm6wH_EC1-&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;_score&quot;</span>: <span class="number">0.6931472</span>,</span><br><span class="line">            <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">                <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;price&quot;</span>: <span class="number">2699</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;3&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;_score&quot;</span>: <span class="number">0.5753642</span>,</span><br><span class="line">            <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">                <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米电视4A&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;price&quot;</span>: <span class="number">3899</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>在上面的案例中，不仅会查询到电视，而且与小米相关的都会查询到，多个词之间是<code>or</code>的关系。</p>
<ul>
<li>and关系</li>
</ul>
<p>某些情况下，我们需要更精确查找，我们希望这个关系变成<code>and</code>，可以这样做：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;match&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;query&quot;</span>: <span class="string">&quot;小米电视&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;operator&quot;</span>: <span class="string">&quot;and&quot;</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">2</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">0.5753642</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;3&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">0.5753642</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米电视4A&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">3899</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>本例中，只有同时包含<code>小米</code>和<code>电视</code>的词条才会被搜索到。</p>
<ul>
<li>or和and之间？</li>
</ul>
<p>在 <code>or</code> 与 <code>and</code> 间二选一有点过于非黑即白。 如果用户给定的条件分词后有 5 个查询词项，想查找只包含其中 4 个词的文档，该如何处理？将 operator 操作符参数设置成 <code>and</code> 只会将此文档排除。</p>
<p>有时候这正是我们期望的，但在全文搜索的大多数应用场景下，我们既想包含那些可能相关的文档，同时又排除那些不太相关的。换句话说，我们想要处于中间某种结果。</p>
<p><code>match</code> 查询支持 <code>minimum_should_match</code> 最小匹配参数， 这让我们可以指定必须匹配的词项数用来表示一个文档是否相关。我们可以将其设置为某个具体数字，更常用的做法是将其设置为一个<code>百分数</code>，因为我们无法控制用户搜索时输入的单词数量：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;match&quot;</span>:&#123;</span><br><span class="line">            <span class="attr">&quot;title&quot;</span>:&#123;</span><br><span class="line">                <span class="attr">&quot;query&quot;</span>:<span class="string">&quot;小米曲面电视&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;minimum_should_match&quot;</span>: <span class="string">&quot;75%&quot;</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>本例中，搜索语句可以分为3个词，如果使用and关系，需要同时满足3个词才会被搜索到。这里我们采用最小品牌数：75%，那么也就是说只要匹配到总词条数量的75%即可，这里3*75% 约等于2。所以只要包含2个词条就算满足条件了。</p>
<p>结果：</p>
<p><img src="assets/1531730367614.png" alt="1531730367614"></p>
<h3 id="3-1-3-多字段查询（multi-match）"><a href="#3-1-3-多字段查询（multi-match）" class="headerlink" title="3.1.3 多字段查询（multi_match）"></a>3.1.3 多字段查询（multi_match）</h3><p><code>multi_match</code>与<code>match</code>类似，不同的是它可以在多个字段中查询</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;multi_match&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;query&quot;</span>:    <span class="string">&quot;小米&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;fields&quot;</span>:   [ <span class="string">&quot;title&quot;</span>, <span class="string">&quot;subTitle&quot;</span> ]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>本例中，我们会在title字段和subtitle字段中查询<code>小米</code>这个词</p>
<h3 id="3-1-4-词条匹配-term"><a href="#3-1-4-词条匹配-term" class="headerlink" title="3.1.4 词条匹配(term)"></a>3.1.4 词条匹配(term)</h3><p><code>term</code> 查询被用于精确值 匹配，这些精确值可能是数字、时间、布尔或者那些<strong>未分词</strong>的字符串</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;term&quot;</span>:&#123;</span><br><span class="line">            <span class="attr">&quot;price&quot;</span>:<span class="number">2699.00</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">2</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;r9c1KGMBIhaxtY5rlRKv&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">2699</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="3-1-5-多词条精确匹配-terms"><a href="#3-1-5-多词条精确匹配-terms" class="headerlink" title="3.1.5 多词条精确匹配(terms)"></a>3.1.5 多词条精确匹配(terms)</h3><p><code>terms</code> 查询和 term 查询一样，但它允许你指定多值进行匹配。如果这个字段包含了指定值中的任何一个值，那么这个文档满足条件：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;terms&quot;</span>:&#123;</span><br><span class="line">            <span class="attr">&quot;price&quot;</span>:[<span class="number">2699.00</span>,<span class="number">2899.00</span>,<span class="number">3899.00</span>]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">4</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;2&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;大米手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">2899</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;r9c1KGMBIhaxtY5rlRKv&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">2699</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;3&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米电视4A&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">3899</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="3-2-结果过滤"><a href="#3-2-结果过滤" class="headerlink" title="3.2.结果过滤"></a>3.2.结果过滤</h2><p>默认情况下，elasticsearch在搜索的结果中，会把文档中保存在<code>_source</code>的所有字段都返回。</p>
<p>如果我们只想获取其中的部分字段，我们可以添加<code>_source</code>的过滤</p>
<h3 id="3-2-1-直接指定字段"><a href="#3-2-1-直接指定字段" class="headerlink" title="3.2.1.直接指定字段"></a>3.2.1.直接指定字段</h3><p>示例：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;_source&quot;</span>: [<span class="string">&quot;title&quot;</span>,<span class="string">&quot;price&quot;</span>],</span><br><span class="line">  <span class="attr">&quot;query&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;term&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;price&quot;</span>: <span class="number">2699</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>返回的结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">12</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;r9c1KGMBIhaxtY5rlRKv&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">2699</span>,</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="3-2-2-指定includes和excludes"><a href="#3-2-2-指定includes和excludes" class="headerlink" title="3.2.2.指定includes和excludes"></a>3.2.2.指定includes和excludes</h3><p>我们也可以通过：</p>
<ul>
<li>includes：来指定想要显示的字段</li>
<li>excludes：来指定不想要显示的字段</li>
</ul>
<p>二者都是可选的。</p>
<p>示例：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;includes&quot;</span>:[<span class="string">&quot;title&quot;</span>,<span class="string">&quot;price&quot;</span>]</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;query&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;term&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;price&quot;</span>: <span class="number">2699</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>与下面的结果将是一样的：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">     <span class="attr">&quot;excludes&quot;</span>: [<span class="string">&quot;images&quot;</span>]</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;query&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;term&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;price&quot;</span>: <span class="number">2699</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="3-3-高级查询"><a href="#3-3-高级查询" class="headerlink" title="3.3 高级查询"></a>3.3 高级查询</h2><h3 id="3-3-1-布尔组合（bool"><a href="#3-3-1-布尔组合（bool" class="headerlink" title="3.3.1 布尔组合（bool)"></a>3.3.1 布尔组合（bool)</h3><p><code>bool</code>把各种其它查询通过<code>must</code>（与）、<code>must_not</code>（非）、<code>should</code>（或）的方式进行组合</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;bool&quot;</span>:&#123;</span><br><span class="line">            <span class="attr">&quot;must&quot;</span>:     &#123; <span class="attr">&quot;match&quot;</span>: &#123; <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;大米&quot;</span> &#125;&#125;,</span><br><span class="line">            <span class="attr">&quot;must_not&quot;</span>: &#123; <span class="attr">&quot;match&quot;</span>: &#123; <span class="attr">&quot;title&quot;</span>:  <span class="string">&quot;电视&quot;</span> &#125;&#125;,</span><br><span class="line">            <span class="attr">&quot;should&quot;</span>:   &#123; <span class="attr">&quot;match&quot;</span>: &#123; <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;手机&quot;</span> &#125;&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">10</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">0.5753642</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;heima&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;goods&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;2&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">0.5753642</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;大米手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">2899</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="3-3-2-范围查询-range"><a href="#3-3-2-范围查询-range" class="headerlink" title="3.3.2 范围查询(range)"></a>3.3.2 范围查询(range)</h3><p><code>range</code> 查询找出那些落在指定区间内的数字或者时间</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;range&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;price&quot;</span>: &#123;</span><br><span class="line">                <span class="attr">&quot;gte&quot;</span>:  <span class="number">1000.0</span>,</span><br><span class="line">                <span class="attr">&quot;lt&quot;</span>:   <span class="number">2800.00</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>range</code>查询允许以下字符：</p>
<table>
<thead>
<tr>
<th align="center">操作符</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">gt</td>
<td align="center">大于</td>
</tr>
<tr>
<td align="center">gte</td>
<td align="center">大于等于</td>
</tr>
<tr>
<td align="center">lt</td>
<td align="center">小于</td>
</tr>
<tr>
<td align="center">lte</td>
<td align="center">小于等于</td>
</tr>
</tbody></table>
<h3 id="3-3-3-模糊查询-fuzzy"><a href="#3-3-3-模糊查询-fuzzy" class="headerlink" title="3.3.3 模糊查询(fuzzy)"></a>3.3.3 模糊查询(fuzzy)</h3><p>我们新增一个商品：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">POST /heima/goods/4</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;title&quot;</span>:<span class="string">&quot;apple手机&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>:<span class="string">&quot;http://image.leyou.com/12479122.jpg&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>:<span class="number">6899.00</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>fuzzy</code> 查询是 <code>term</code> 查询的模糊等价。它允许用户搜索词条与实际词条的拼写出现偏差，但是偏差的编辑距离不得超过2：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;query&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;fuzzy&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;appla&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的查询，也能查询到apple手机</p>
<p>我们可以通过<code>fuzziness</code>来指定允许的编辑距离：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;query&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;fuzzy&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;title&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;value&quot;</span>:<span class="string">&quot;appla&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;fuzziness&quot;</span>:<span class="number">1</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="3-4-过滤-filter"><a href="#3-4-过滤-filter" class="headerlink" title="3.4 过滤(filter)"></a>3.4 过滤(filter)</h2><blockquote>
<p><strong>条件查询中进行过滤</strong></p>
</blockquote>
<p>所有的查询都会影响到文档的评分及排名。如果我们需要在查询结果中进行过滤，并且不希望过滤条件影响评分，那么就不要把过滤条件作为查询条件来用。而是使用<code>filter</code>方式：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;bool&quot;</span>:&#123;</span><br><span class="line">            <span class="attr">&quot;must&quot;</span>:&#123; <span class="attr">&quot;match&quot;</span>: &#123; <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机&quot;</span> &#125;&#125;,</span><br><span class="line">            <span class="attr">&quot;filter&quot;</span>:&#123;</span><br><span class="line">                <span class="attr">&quot;range&quot;</span>:&#123;<span class="attr">&quot;price&quot;</span>:&#123;<span class="attr">&quot;gt&quot;</span>:<span class="number">2000.00</span>,<span class="attr">&quot;lt&quot;</span>:<span class="number">3800.00</span>&#125;&#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意：<code>filter</code>中还可以再次进行<code>bool</code>组合条件过滤。</p>
<blockquote>
<p><strong>无查询条件，直接过滤</strong></p>
</blockquote>
<p>如果一次查询只有过滤，没有查询条件，不希望进行评分，我们可以使用<code>constant_score</code>取代只有 filter 语句的 bool 查询。在性能上是完全相同的，但对于提高查询简洁性和清晰度有很大帮助。</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;constant_score&quot;</span>:   &#123;</span><br><span class="line">            <span class="attr">&quot;filter&quot;</span>: &#123;</span><br><span class="line">                 <span class="attr">&quot;range&quot;</span>:&#123;<span class="attr">&quot;price&quot;</span>:&#123;<span class="attr">&quot;gt&quot;</span>:<span class="number">2000.00</span>,<span class="attr">&quot;lt&quot;</span>:<span class="number">3000.00</span>&#125;&#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="3-5-排序"><a href="#3-5-排序" class="headerlink" title="3.5 排序"></a>3.5 排序</h2><h3 id="3-4-1-单字段排序"><a href="#3-4-1-单字段排序" class="headerlink" title="3.4.1 单字段排序"></a>3.4.1 单字段排序</h3><p><code>sort</code> 可以让我们按照不同的字段进行排序，并且通过<code>order</code>指定排序的方式</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">GET /heima/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;query&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;match&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;sort&quot;</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">&quot;price&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;order&quot;</span>: <span class="string">&quot;desc&quot;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="3-4-2-多字段排序"><a href="#3-4-2-多字段排序" class="headerlink" title="3.4.2 多字段排序"></a>3.4.2 多字段排序</h3><p>假定我们想要结合使用 price和 _score（得分） 进行查询，并且匹配的结果首先按照价格排序，然后按照相关性得分排序：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">GET /goods/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;query&quot;</span>:&#123;</span><br><span class="line">        <span class="attr">&quot;bool&quot;</span>:&#123;</span><br><span class="line">            <span class="attr">&quot;must&quot;</span>:&#123; <span class="attr">&quot;match&quot;</span>: &#123; <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机&quot;</span> &#125;&#125;,</span><br><span class="line">            <span class="attr">&quot;filter&quot;</span>:&#123;</span><br><span class="line">                <span class="attr">&quot;range&quot;</span>:&#123;<span class="attr">&quot;price&quot;</span>:&#123;<span class="attr">&quot;gt&quot;</span>:<span class="number">200000</span>,<span class="attr">&quot;lt&quot;</span>:<span class="number">300000</span>&#125;&#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">&quot;sort&quot;</span>: [</span><br><span class="line">      &#123; <span class="attr">&quot;price&quot;</span>: &#123; <span class="attr">&quot;order&quot;</span>: <span class="string">&quot;desc&quot;</span> &#125;&#125;,</span><br><span class="line">      &#123; <span class="attr">&quot;_score&quot;</span>: &#123; <span class="attr">&quot;order&quot;</span>: <span class="string">&quot;desc&quot;</span> &#125;&#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="4-聚合aggregations"><a href="#4-聚合aggregations" class="headerlink" title="4. 聚合aggregations"></a>4. 聚合aggregations</h1><p>聚合可以让我们极其方便的实现对数据的统计、分析。例如：</p>
<ul>
<li>什么品牌的手机最受欢迎？</li>
<li>这些手机的平均价格、最高价格、最低价格？</li>
<li>这些手机每月的销售情况如何？</li>
</ul>
<p>实现这些统计功能的比数据库的sql要方便的多，而且查询速度非常快，可以实现实时搜索效果。</p>
<h2 id="4-1-基本概念"><a href="#4-1-基本概念" class="headerlink" title="4.1 基本概念"></a>4.1 基本概念</h2><p>Elasticsearch中的聚合，包含多种类型，最常用的两种，一个叫<code>桶</code>，一个叫<code>度量</code>：</p>
<blockquote>
<p><strong>桶（bucket）</strong></p>
</blockquote>
<p>桶的作用，是按照某种方式对数据进行分组，每一组数据在ES中称为一个<code>桶</code>，例如我们根据国籍对人划分，可以得到<code>中国桶</code>、<code>英国桶</code>，<code>日本桶</code>……或者我们按照年龄段对人进行划分：0<del>10,10</del>20,20<del>30,30</del>40等。</p>
<p>Elasticsearch中提供的划分桶的方式有很多：</p>
<ul>
<li>Date Histogram Aggregation：根据日期阶梯分组，例如给定阶梯为周，会自动每周分为一组</li>
<li>Histogram Aggregation：根据数值阶梯分组，与日期类似</li>
<li>Terms Aggregation：根据词条内容分组，词条内容完全匹配的为一组</li>
<li>Range Aggregation：数值和日期的范围分组，指定开始和结束，然后按段分组</li>
<li>……</li>
</ul>
<p>综上所述，我们发现bucket aggregations 只负责对数据进行分组，并不进行计算，因此往往bucket中往往会嵌套另一种聚合：metrics aggregations即度量</p>
<blockquote>
<p><strong>度量（metrics）</strong></p>
</blockquote>
<p>分组完成以后，我们一般会对组中的数据进行聚合运算，例如求平均值、最大、最小、求和等，这些在ES中称为<code>度量</code></p>
<p>比较常用的一些度量聚合方式：</p>
<ul>
<li>Avg Aggregation：求平均值</li>
<li>Max Aggregation：求最大值</li>
<li>Min Aggregation：求最小值</li>
<li>Percentiles Aggregation：求百分比</li>
<li>Stats Aggregation：同时返回avg、max、min、sum、count等</li>
<li>Sum Aggregation：求和</li>
<li>Top hits Aggregation：求前几</li>
<li>Value Count Aggregation：求总数</li>
<li>……</li>
</ul>
<p>为了测试聚合，我们先批量导入一些数据</p>
<p>创建索引：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">PUT /cars</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;settings&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;number_of_shards&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;number_of_replicas&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;mappings&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;transactions&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;properties&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;color&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;keyword&quot;</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">&quot;make&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;keyword&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意</strong>：在ES中，需要进行聚合、排序、过滤的字段其处理方式比较特殊，因此不能被分词。这里我们将color和make这两个文字类型的字段设置为keyword类型，这个类型不会被分词，将来就可以参与聚合</p>
<p>导入数据</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">POST /cars/transactions/_bulk</span><br><span class="line">&#123; <span class="attr">&quot;index&quot;</span>: &#123;&#125;&#125;</span><br><span class="line">&#123; <span class="attr">&quot;price&quot;</span> : <span class="number">10000</span>, <span class="attr">&quot;color&quot;</span> : <span class="string">&quot;red&quot;</span>, <span class="attr">&quot;make&quot;</span> : <span class="string">&quot;honda&quot;</span>, <span class="attr">&quot;sold&quot;</span> : <span class="string">&quot;2014-10-28&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">&quot;index&quot;</span>: &#123;&#125;&#125;</span><br><span class="line">&#123; <span class="attr">&quot;price&quot;</span> : <span class="number">20000</span>, <span class="attr">&quot;color&quot;</span> : <span class="string">&quot;red&quot;</span>, <span class="attr">&quot;make&quot;</span> : <span class="string">&quot;honda&quot;</span>, <span class="attr">&quot;sold&quot;</span> : <span class="string">&quot;2014-11-05&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">&quot;index&quot;</span>: &#123;&#125;&#125;</span><br><span class="line">&#123; <span class="attr">&quot;price&quot;</span> : <span class="number">30000</span>, <span class="attr">&quot;color&quot;</span> : <span class="string">&quot;green&quot;</span>, <span class="attr">&quot;make&quot;</span> : <span class="string">&quot;ford&quot;</span>, <span class="attr">&quot;sold&quot;</span> : <span class="string">&quot;2014-05-18&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">&quot;index&quot;</span>: &#123;&#125;&#125;</span><br><span class="line">&#123; <span class="attr">&quot;price&quot;</span> : <span class="number">15000</span>, <span class="attr">&quot;color&quot;</span> : <span class="string">&quot;blue&quot;</span>, <span class="attr">&quot;make&quot;</span> : <span class="string">&quot;toyota&quot;</span>, <span class="attr">&quot;sold&quot;</span> : <span class="string">&quot;2014-07-02&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">&quot;index&quot;</span>: &#123;&#125;&#125;</span><br><span class="line">&#123; <span class="attr">&quot;price&quot;</span> : <span class="number">12000</span>, <span class="attr">&quot;color&quot;</span> : <span class="string">&quot;green&quot;</span>, <span class="attr">&quot;make&quot;</span> : <span class="string">&quot;toyota&quot;</span>, <span class="attr">&quot;sold&quot;</span> : <span class="string">&quot;2014-08-19&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">&quot;index&quot;</span>: &#123;&#125;&#125;</span><br><span class="line">&#123; <span class="attr">&quot;price&quot;</span> : <span class="number">20000</span>, <span class="attr">&quot;color&quot;</span> : <span class="string">&quot;red&quot;</span>, <span class="attr">&quot;make&quot;</span> : <span class="string">&quot;honda&quot;</span>, <span class="attr">&quot;sold&quot;</span> : <span class="string">&quot;2014-11-05&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">&quot;index&quot;</span>: &#123;&#125;&#125;</span><br><span class="line">&#123; <span class="attr">&quot;price&quot;</span> : <span class="number">80000</span>, <span class="attr">&quot;color&quot;</span> : <span class="string">&quot;red&quot;</span>, <span class="attr">&quot;make&quot;</span> : <span class="string">&quot;bmw&quot;</span>, <span class="attr">&quot;sold&quot;</span> : <span class="string">&quot;2014-01-01&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">&quot;index&quot;</span>: &#123;&#125;&#125;</span><br><span class="line">&#123; <span class="attr">&quot;price&quot;</span> : <span class="number">25000</span>, <span class="attr">&quot;color&quot;</span> : <span class="string">&quot;blue&quot;</span>, <span class="attr">&quot;make&quot;</span> : <span class="string">&quot;ford&quot;</span>, <span class="attr">&quot;sold&quot;</span> : <span class="string">&quot;2014-02-12&quot;</span> &#125;</span><br></pre></td></tr></table></figure>



<h2 id="4-2-聚合为桶"><a href="#4-2-聚合为桶" class="headerlink" title="4.2 聚合为桶"></a>4.2 聚合为桶</h2><p>首先，我们按照 汽车的颜色<code>color</code>来划分<code>桶</code></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">GET /cars/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;size&quot;</span> : <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;aggs&quot;</span> : &#123; </span><br><span class="line">        <span class="attr">&quot;popular_colors&quot;</span> : &#123; </span><br><span class="line">            <span class="attr">&quot;terms&quot;</span> : &#123; </span><br><span class="line">              <span class="attr">&quot;field&quot;</span> : <span class="string">&quot;color&quot;</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>size： 查询条数，这里设置为0，因为我们不关心搜索到的数据，只关心聚合结果，提高效率</li>
<li>aggs：声明这是一个聚合查询，是aggregations的缩写<ul>
<li>popular_colors：给这次聚合起一个名字，任意。<ul>
<li>terms：划分桶的方式，这里是根据词条划分<ul>
<li>field：划分桶的字段</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">8</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: []</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;aggregations&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;popular_colors&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;doc_count_error_upper_bound&quot;</span>: <span class="number">0</span>,</span><br><span class="line">      <span class="attr">&quot;sum_other_doc_count&quot;</span>: <span class="number">0</span>,</span><br><span class="line">      <span class="attr">&quot;buckets&quot;</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;red&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">4</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;blue&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;green&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>hits：查询结果为空，因为我们设置了size为0</li>
<li>aggregations：聚合的结果</li>
<li>popular_colors：我们定义的聚合名称</li>
<li>buckets：查找到的桶，每个不同的color字段值都会形成一个桶<ul>
<li>key：这个桶对应的color字段的值</li>
<li>doc_count：这个桶中的文档数量</li>
</ul>
</li>
</ul>
<p>通过聚合的结果我们发现，目前红色的小车比较畅销！</p>
<h2 id="4-3-桶内度量"><a href="#4-3-桶内度量" class="headerlink" title="4.3 桶内度量"></a>4.3 桶内度量</h2><p>前面的例子告诉我们每个桶里面的文档数量，这很有用。 但通常，我们的应用需要提供更复杂的文档度量。 例如，每种颜色汽车的平均价格是多少？</p>
<p>因此，我们需要告诉Elasticsearch<code>使用哪个字段</code>，<code>使用何种度量方式</code>进行运算，这些信息要嵌套在<code>桶</code>内，<code>度量</code>的运算会基于<code>桶</code>内的文档进行</p>
<p>现在，我们为刚刚的聚合结果添加 求价格平均值的度量：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">GET /cars/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;size&quot;</span> : <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;aggs&quot;</span> : &#123; </span><br><span class="line">        <span class="attr">&quot;popular_colors&quot;</span> : &#123; </span><br><span class="line">            <span class="attr">&quot;terms&quot;</span> : &#123; </span><br><span class="line">              <span class="attr">&quot;field&quot;</span> : <span class="string">&quot;color&quot;</span></span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="attr">&quot;aggs&quot;</span>:&#123;</span><br><span class="line">                <span class="attr">&quot;avg_price&quot;</span>: &#123; </span><br><span class="line">                   <span class="attr">&quot;avg&quot;</span>: &#123;</span><br><span class="line">                      <span class="attr">&quot;field&quot;</span>: <span class="string">&quot;price&quot;</span> </span><br><span class="line">                   &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>aggs：我们在上一个aggs(popular_colors)中添加新的aggs。可见<code>度量</code>也是一个聚合,度量是在桶内的聚合</li>
<li>avg_price：聚合的名称</li>
<li>avg：度量的类型，这里是求平均值</li>
<li>field：度量运算的字段</li>
</ul>
<p>结果：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">  &quot;aggregations&quot;: &#123;</span><br><span class="line">    &quot;popular_colors&quot;: &#123;</span><br><span class="line">      &quot;doc_count_error_upper_bound&quot;: 0,</span><br><span class="line">      &quot;sum_other_doc_count&quot;: 0,</span><br><span class="line">      &quot;buckets&quot;: [</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;red&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">4</span>,</span><br><span class="line">          <span class="attr">&quot;avg_price&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;value&quot;</span>: <span class="number">32500</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;blue&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span>,</span><br><span class="line">          <span class="attr">&quot;avg_price&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;value&quot;</span>: <span class="number">20000</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;green&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span>,</span><br><span class="line">          <span class="attr">&quot;avg_price&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;value&quot;</span>: <span class="number">21000</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p>可以看到每个桶中都有自己的<code>avg_price</code>字段，这是度量聚合的结果</p>
<h2 id="4-4-桶内嵌套桶"><a href="#4-4-桶内嵌套桶" class="headerlink" title="4.4 桶内嵌套桶"></a>4.4 桶内嵌套桶</h2><p>刚刚的案例中，我们在桶内嵌套度量运算。事实上桶不仅可以嵌套运算， 还可以再嵌套其它桶。也就是说在每个分组中，再分更多组。</p>
<p>比如：我们想统计每种颜色的汽车中，分别属于哪个制造商，按照<code>make</code>字段再进行分桶</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">GET /cars/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;size&quot;</span> : <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;aggs&quot;</span> : &#123; </span><br><span class="line">        <span class="attr">&quot;popular_colors&quot;</span> : &#123; </span><br><span class="line">            <span class="attr">&quot;terms&quot;</span> : &#123; </span><br><span class="line">              <span class="attr">&quot;field&quot;</span> : <span class="string">&quot;color&quot;</span></span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="attr">&quot;aggs&quot;</span>:&#123;</span><br><span class="line">                <span class="attr">&quot;avg_price&quot;</span>: &#123; </span><br><span class="line">                   <span class="attr">&quot;avg&quot;</span>: &#123;</span><br><span class="line">                      <span class="attr">&quot;field&quot;</span>: <span class="string">&quot;price&quot;</span> </span><br><span class="line">                   &#125;</span><br><span class="line">                &#125;,</span><br><span class="line">                <span class="attr">&quot;maker&quot;</span>:&#123;</span><br><span class="line">                    <span class="attr">&quot;terms&quot;</span>:&#123;</span><br><span class="line">                        <span class="attr">&quot;field&quot;</span>:<span class="string">&quot;make&quot;</span></span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>原来的color桶和avg计算我们不变</li>
<li>maker：在嵌套的aggs下新添一个桶，叫做maker</li>
<li>terms：桶的划分类型依然是词条</li>
<li>filed：这里根据make字段进行划分</li>
</ul>
<p>部分结果：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">&#123;<span class="attr">&quot;aggregations&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;popular_colors&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;doc_count_error_upper_bound&quot;</span>: <span class="number">0</span>,</span><br><span class="line">      <span class="attr">&quot;sum_other_doc_count&quot;</span>: <span class="number">0</span>,</span><br><span class="line">      <span class="attr">&quot;buckets&quot;</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;red&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">4</span>,</span><br><span class="line">          <span class="attr">&quot;maker&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;doc_count_error_upper_bound&quot;</span>: <span class="number">0</span>,</span><br><span class="line">            <span class="attr">&quot;sum_other_doc_count&quot;</span>: <span class="number">0</span>,</span><br><span class="line">            <span class="attr">&quot;buckets&quot;</span>: [</span><br><span class="line">              &#123;</span><br><span class="line">                <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;honda&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;doc_count&quot;</span>: <span class="number">3</span></span><br><span class="line">              &#125;,</span><br><span class="line">              &#123;</span><br><span class="line">                <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;bmw&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">              &#125;</span><br><span class="line">            ]</span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;avg_price&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;value&quot;</span>: <span class="number">32500</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;blue&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span>,</span><br><span class="line">          <span class="attr">&quot;maker&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;doc_count_error_upper_bound&quot;</span>: <span class="number">0</span>,</span><br><span class="line">            <span class="attr">&quot;sum_other_doc_count&quot;</span>: <span class="number">0</span>,</span><br><span class="line">            <span class="attr">&quot;buckets&quot;</span>: [</span><br><span class="line">              &#123;</span><br><span class="line">                <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;ford&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">              &#125;,</span><br><span class="line">              &#123;</span><br><span class="line">                <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;toyota&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">              &#125;</span><br><span class="line">            ]</span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;avg_price&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;value&quot;</span>: <span class="number">20000</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;green&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span>,</span><br><span class="line">          <span class="attr">&quot;maker&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;doc_count_error_upper_bound&quot;</span>: <span class="number">0</span>,</span><br><span class="line">            <span class="attr">&quot;sum_other_doc_count&quot;</span>: <span class="number">0</span>,</span><br><span class="line">            <span class="attr">&quot;buckets&quot;</span>: [</span><br><span class="line">              &#123;</span><br><span class="line">                <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;ford&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">              &#125;,</span><br><span class="line">              &#123;</span><br><span class="line">                <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;toyota&quot;</span>,</span><br><span class="line">                <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">              &#125;</span><br><span class="line">            ]</span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;avg_price&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;value&quot;</span>: <span class="number">21000</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<ul>
<li>我们可以看到，新的聚合<code>maker</code>被嵌套在原来每一个<code>color</code>的桶中。</li>
<li>每个颜色下面都根据 <code>make</code>字段进行了分组</li>
<li>我们能读取到的信息：<ul>
<li>红色车共有4辆</li>
<li>红色车的平均售价是 $32，500 美元。</li>
<li>其中3辆是 Honda 本田制造，1辆是 BMW 宝马制造。</li>
</ul>
</li>
</ul>
<h2 id="4-5-划分桶的其它方式"><a href="#4-5-划分桶的其它方式" class="headerlink" title="4.5.划分桶的其它方式"></a>4.5.划分桶的其它方式</h2><p>前面讲了，划分桶的方式有很多，例如：</p>
<ul>
<li>Date Histogram Aggregation：根据日期阶梯分组，例如给定阶梯为周，会自动每周分为一组</li>
<li>Histogram Aggregation：根据数值阶梯分组，与日期类似</li>
<li>Terms Aggregation：根据词条内容分组，词条内容完全匹配的为一组</li>
<li>Range Aggregation：数值和日期的范围分组，指定开始和结束，然后按段分组</li>
</ul>
<p>刚刚的案例中，我们采用的是Terms Aggregation，即根据词条划分桶。</p>
<p>接下来，我们再学习几个比较实用的：</p>
<h3 id="4-5-1-阶梯分桶Histogram"><a href="#4-5-1-阶梯分桶Histogram" class="headerlink" title="4.5.1.阶梯分桶Histogram"></a>4.5.1.阶梯分桶Histogram</h3><blockquote>
<p>原理：</p>
</blockquote>
<p>histogram是把数值类型的字段，按照一定的阶梯大小进行分组。你需要指定一个阶梯值（interval）来划分阶梯大小。</p>
<p>举例：</p>
<p>比如你有价格字段，如果你设定interval的值为200，那么阶梯就会是这样的：</p>
<p>0，200，400，600，…</p>
<p>上面列出的是每个阶梯的key，也是区间的启点。</p>
<p>如果一件商品的价格是450，会落入哪个阶梯区间呢？计算公式如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">bucket_key &#x3D; Math.floor((value - offset) &#x2F; interval) * interval + offset</span><br></pre></td></tr></table></figure>

<p>value：就是当前数据的值，本例中是450</p>
<p>offset：起始偏移量，默认为0</p>
<p>interval：阶梯间隔，比如200</p>
<p>因此你得到的key = Math.floor((450 - 0) / 200) * 200 + 0 = 400</p>
<blockquote>
<p>操作一下：</p>
</blockquote>
<p>比如，我们对汽车的价格进行分组，指定间隔interval为5000：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">GET /cars/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;size&quot;</span>:<span class="number">0</span>,</span><br><span class="line">  <span class="attr">&quot;aggs&quot;</span>:&#123;</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>:&#123;</span><br><span class="line">      <span class="attr">&quot;histogram&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;field&quot;</span>: <span class="string">&quot;price&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;interval&quot;</span>: <span class="number">5000</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">21</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">5</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">5</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">8</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: []</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;aggregations&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;buckets&quot;</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">10000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">15000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">20000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">25000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">30000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">35000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">0</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">40000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">0</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">45000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">0</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">50000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">0</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">55000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">0</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">60000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">0</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">65000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">0</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">70000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">0</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">75000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">0</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">80000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">        &#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你会发现，中间有大量的文档数量为0 的桶，看起来很丑。</p>
<p>我们可以增加一个参数min_doc_count为1，来约束最少文档数量为1，这样文档数量为0的桶会被过滤</p>
<p>示例：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">GET /cars/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;size&quot;</span>:<span class="number">0</span>,</span><br><span class="line">  <span class="attr">&quot;aggs&quot;</span>:&#123;</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>:&#123;</span><br><span class="line">      <span class="attr">&quot;histogram&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;field&quot;</span>: <span class="string">&quot;price&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;interval&quot;</span>: <span class="number">5000</span>,</span><br><span class="line">        <span class="attr">&quot;min_doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">15</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">5</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">5</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">8</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: []</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;aggregations&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;buckets&quot;</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">10000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">15000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">20000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">2</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">25000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">30000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="number">80000</span>,</span><br><span class="line">          <span class="attr">&quot;doc_count&quot;</span>: <span class="number">1</span></span><br><span class="line">        &#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>完美，！</p>
<p>如果你用kibana将结果变为柱形图，会更好看：</p>
<p><img src="assets/1531752558505.png" alt="1531752558505"></p>
<h3 id="4-5-2-范围分桶range"><a href="#4-5-2-范围分桶range" class="headerlink" title="4.5.2.范围分桶range"></a>4.5.2.范围分桶range</h3><p>范围分桶与阶梯分桶类似，也是把数字按照阶段进行分组，只不过range方式需要你自己指定每一组的起始和结束大小。</p>
<h1 id="5-Spring-Data-Elasticsearch"><a href="#5-Spring-Data-Elasticsearch" class="headerlink" title="5.Spring Data Elasticsearch"></a>5.Spring Data Elasticsearch</h1><p>Elasticsearch提供的Java客户端有一些不太方便的地方：</p>
<ul>
<li>很多地方需要拼接Json字符串，在java中拼接字符串有多恐怖你应该懂的</li>
<li>需要自己把对象序列化为json存储</li>
<li>查询到结果也需要自己反序列化为对象</li>
</ul>
<p>因此，我们这里就不讲解原生的Elasticsearch客户端API了。</p>
<p>而是学习Spring提供的套件：Spring Data Elasticsearch。</p>
<h2 id="5-1-简介"><a href="#5-1-简介" class="headerlink" title="5.1.简介"></a>5.1.简介</h2><p>Spring Data Elasticsearch是Spring Data项目下的一个子模块。</p>
<p>查看 Spring Data的官网：<a target="_blank" rel="noopener" href="http://projects.spring.io/spring-data/">http://projects.spring.io/spring-data/</a></p>
<p><img src="assets/1531753066475.png" alt="1531753066475"></p>
<blockquote>
<p>Spring Data的使命是为数据访问提供熟悉且一致的基于Spring的编程模型，同时仍保留底层数据存储的特殊特性。</p>
<p>它使得使用数据访问技术，关系数据库和非关系数据库，map-reduce框架和基于云的数据服务变得容易。这是一个总括项目，其中包含许多特定于给定数据库的子项目。这些令人兴奋的技术项目背后，是由许多公司和开发人员合作开发的。</p>
</blockquote>
<p>Spring Data 的使命是给各种数据访问提供统一的编程接口，不管是关系型数据库（如MySQL），还是非关系数据库（如Redis），或者类似Elasticsearch这样的索引数据库。从而简化开发人员的代码，提高开发效率。</p>
<p>包含很多不同数据操作的模块：</p>
<p><img src="assets/1531753715580.png" alt="1531753715580"></p>
<p>Spring Data Elasticsearch的页面：<a target="_blank" rel="noopener" href="https://projects.spring.io/spring-data-elasticsearch/">https://projects.spring.io/spring-data-elasticsearch/</a></p>
<p> <img src="assets/1531754111583.png" alt="1531754111583"></p>
<p>特征：</p>
<ul>
<li>支持Spring的基于<code>@Configuration</code>的java配置方式，或者XML配置方式</li>
<li>提供了用于操作ES的便捷工具类**<code>ElasticsearchTemplate</code>**。包括实现文档到POJO之间的自动智能映射。</li>
<li>利用Spring的数据转换服务实现的功能丰富的对象映射</li>
<li>基于注解的元数据映射方式，而且可扩展以支持更多不同的数据格式</li>
<li>根据持久层接口自动生成对应实现方法，无需人工编写基本操作代码（类似mybatis，根据接口自动得到实现）。当然，也支持人工定制查询</li>
</ul>
<h2 id="5-2-创建Demo工程"><a href="#5-2-创建Demo工程" class="headerlink" title="5.2.创建Demo工程"></a>5.2.创建Demo工程</h2><p>我们新建一个demo，学习Elasticsearch</p>
<p><img src="assets/1531973082475.png" alt="1531973082475"></p>
<p><img src="assets/1531974312212.png" alt="1531974312212"></p>
<p>pom依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span> <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.leyou.demo<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>elasticsearch<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">packaging</span>&gt;</span>jar<span class="tag">&lt;/<span class="name">packaging</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">name</span>&gt;</span>elasticsearch<span class="tag">&lt;/<span class="name">name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">description</span>&gt;</span>Demo project for Spring Boot<span class="tag">&lt;/<span class="name">description</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">parent</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.0.2.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">relativePath</span>/&gt;</span> <span class="comment">&lt;!-- lookup parent from repository --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">parent</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">properties</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">project.build.sourceEncoding</span>&gt;</span>UTF-8<span class="tag">&lt;/<span class="name">project.build.sourceEncoding</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">project.reporting.outputEncoding</span>&gt;</span>UTF-8<span class="tag">&lt;/<span class="name">project.reporting.outputEncoding</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">java.version</span>&gt;</span>1.8<span class="tag">&lt;/<span class="name">java.version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-elasticsearch<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">build</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">plugins</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">plugin</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-maven-plugin<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">plugin</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">plugins</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">build</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>application.yml文件配置：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">data:</span></span><br><span class="line">    <span class="attr">elasticsearch:</span></span><br><span class="line">      <span class="attr">cluster-name:</span> <span class="string">elasticsearch</span></span><br><span class="line">      <span class="attr">cluster-nodes:</span> <span class="number">192.168</span><span class="number">.56</span><span class="number">.101</span><span class="string">:9300</span></span><br></pre></td></tr></table></figure>



<h2 id="5-3-实体类及注解"><a href="#5-3-实体类及注解" class="headerlink" title="5.3.实体类及注解"></a>5.3.实体类及注解</h2><p>首先我们准备好实体类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Item</span> </span>&#123;</span><br><span class="line">    Long id;</span><br><span class="line">    String title; <span class="comment">//标题</span></span><br><span class="line">    String category;<span class="comment">// 分类</span></span><br><span class="line">    String brand; <span class="comment">// 品牌</span></span><br><span class="line">    Double price; <span class="comment">// 价格</span></span><br><span class="line">    String images; <span class="comment">// 图片地址</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>映射</p>
</blockquote>
<p>Spring Data通过注解来声明字段的映射属性，有下面的三个注解：</p>
<ul>
<li><code>@Document</code> 作用在类，标记实体类为文档对象，一般有两个属性<ul>
<li>indexName：对应索引库名称</li>
<li>type：对应在索引库中的类型</li>
<li>shards：分片数量，默认5</li>
<li>replicas：副本数量，默认1</li>
</ul>
</li>
<li><code>@Id</code> 作用在成员变量，标记一个字段作为id主键</li>
<li><code>@Field</code> 作用在成员变量，标记为文档的字段，并指定字段映射属性：<ul>
<li>type：字段类型，取值是枚举：FieldType</li>
<li>index：是否索引，布尔类型，默认是true</li>
<li>store：是否存储，布尔类型，默认是false</li>
<li>analyzer：分词器名称</li>
</ul>
</li>
</ul>
<p>示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Document(indexName = &quot;item&quot;,type = &quot;docs&quot;, shards = 1, replicas = 0)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Item</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Id</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Field(type = FieldType.Text, analyzer = &quot;ik_max_word&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String title; <span class="comment">//标题</span></span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Field(type = FieldType.Keyword)</span></span><br><span class="line">    <span class="keyword">private</span> String category;<span class="comment">// 分类</span></span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Field(type = FieldType.Keyword)</span></span><br><span class="line">    <span class="keyword">private</span> String brand; <span class="comment">// 品牌</span></span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Field(type = FieldType.Double)</span></span><br><span class="line">    <span class="keyword">private</span> Double price; <span class="comment">// 价格</span></span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Field(index = false, type = FieldType.Keyword)</span></span><br><span class="line">    <span class="keyword">private</span> String images; <span class="comment">// 图片地址</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="5-4-Template索引操作"><a href="#5-4-Template索引操作" class="headerlink" title="5.4.Template索引操作"></a>5.4.Template索引操作</h2><h3 id="5-4-1-创建索引和映射"><a href="#5-4-1-创建索引和映射" class="headerlink" title="5.4.1.创建索引和映射"></a>5.4.1.创建索引和映射</h3><blockquote>
<p>创建索引</p>
</blockquote>
<p> <img src="assets/1531985485904.png" alt="1531985485904"></p>
<p>ElasticsearchTemplate中提供了创建索引的API：</p>
<p><img src="assets/1531984923727.png" alt="1531984923727"></p>
<p>可以根据类的信息自动生成，也可以手动指定indexName和Settings</p>
<blockquote>
<p>映射</p>
</blockquote>
<p>映射相关的API：</p>
<p><img src="assets/1531985337698.png" alt="1531985337698"></p>
<p>可以根据类的字节码信息（注解配置）来生成映射，或者手动编写映射</p>
<p>我们这里采用类的字节码信息创建索引并映射：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RunWith(SpringRunner.class)</span></span><br><span class="line"><span class="meta">@SpringBootTest(classes = ItcastElasticsearchApplication.class)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IndexTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> ElasticsearchTemplate elasticsearchTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testCreate</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">// 创建索引，会根据Item类的@Document注解信息来创建</span></span><br><span class="line">        elasticsearchTemplate.createIndex(Item.class);</span><br><span class="line">        <span class="comment">// 配置映射，会根据Item类中的id、Field等字段来自动完成映射</span></span><br><span class="line">        elasticsearchTemplate.putMapping(Item.class);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">GET /item</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;item&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;aliases&quot;</span>: &#123;&#125;,</span><br><span class="line">    <span class="attr">&quot;mappings&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;docs&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;properties&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;brand&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;keyword&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;category&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;keyword&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;keyword&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;index&quot;</span>: <span class="literal">false</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;double&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;text&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;analyzer&quot;</span>: <span class="string">&quot;ik_max_word&quot;</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">&quot;settings&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;index&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;refresh_interval&quot;</span>: <span class="string">&quot;1s&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;number_of_shards&quot;</span>: <span class="string">&quot;1&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;provided_name&quot;</span>: <span class="string">&quot;item&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;creation_date&quot;</span>: <span class="string">&quot;1525405022589&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;store&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;fs&quot;</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">&quot;number_of_replicas&quot;</span>: <span class="string">&quot;0&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;uuid&quot;</span>: <span class="string">&quot;4sE9SAw3Sqq1aAPz5F6OEg&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;version&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;created&quot;</span>: <span class="string">&quot;6020499&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="5-3-2-删除索引"><a href="#5-3-2-删除索引" class="headerlink" title="5.3.2.删除索引"></a>5.3.2.删除索引</h3><p>删除索引的API：</p>
<p><img src="assets/1531986474606.png" alt="1526544759120"></p>
<p>可以根据类名或索引名删除。</p>
<p>示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteIndex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    esTemplate.deleteIndex(<span class="string">&quot;heima&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<p> <img src="assets/1531986618059.png" alt="1531986618059"></p>
<h2 id="5-4-Repository文档操作"><a href="#5-4-Repository文档操作" class="headerlink" title="5.4.Repository文档操作"></a>5.4.Repository文档操作</h2><p>Spring Data 的强大之处，就在于你不用写任何DAO处理，自动根据方法名或类的信息进行CRUD操作。只要你定义一个接口，然后继承Repository提供的一些子接口，就能具备各种基本的CRUD功能。</p>
<p>我们只需要定义接口，然后继承它就OK了。</p>
<p> <img src="../../../../%E6%95%99%E5%AD%A6/leyou1/day11/%E7%AC%94%E8%AE%B0/assets/1531987244855.png" alt="1531987244855"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ItemRepository</span> <span class="keyword">extends</span> <span class="title">ElasticsearchRepository</span>&lt;<span class="title">Item</span>,<span class="title">Long</span>&gt; </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="G:\SSM\ssm\乐优\乐优商城《项目笔记》\day11笔记\assets\1531987244855.png"></p>
<p>来看下Repository的继承关系：</p>
<p> <img src="assets/1531986965570.png" alt="1531986965570"></p>
<p>我们看到有一个ElasticsearchRepository接口：</p>
<p><img src="assets/1531987044693.png" alt="1531987044693"></p>
<h3 id="5-4-1-新增文档"><a href="#5-4-1-新增文档" class="headerlink" title="5.4.1.新增文档"></a>5.4.1.新增文档</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> ItemRepository itemRepository;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">index</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Item item = <span class="keyword">new</span> Item(<span class="number">1L</span>, <span class="string">&quot;小米手机7&quot;</span>, <span class="string">&quot; 手机&quot;</span>,</span><br><span class="line">                         <span class="string">&quot;小米&quot;</span>, <span class="number">3499.00</span>, <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span>);</span><br><span class="line">    itemRepository.save(item);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>去页面查询看看：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GET &#x2F;item&#x2F;_search</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">14</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;item&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;docs&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;1&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;id&quot;</span>: <span class="number">1</span>,</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机7&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;category&quot;</span>: <span class="string">&quot; 手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;brand&quot;</span>: <span class="string">&quot;小米&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">3499</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="5-4-2-批量新增"><a href="#5-4-2-批量新增" class="headerlink" title="5.4.2.批量新增"></a>5.4.2.批量新增</h3><p>代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">indexList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    List&lt;Item&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    list.add(<span class="keyword">new</span> Item(<span class="number">2L</span>, <span class="string">&quot;坚果手机R1&quot;</span>, <span class="string">&quot; 手机&quot;</span>, <span class="string">&quot;锤子&quot;</span>, <span class="number">3699.00</span>, <span class="string">&quot;http://image.leyou.com/123.jpg&quot;</span>));</span><br><span class="line">    list.add(<span class="keyword">new</span> Item(<span class="number">3L</span>, <span class="string">&quot;华为META10&quot;</span>, <span class="string">&quot; 手机&quot;</span>, <span class="string">&quot;华为&quot;</span>, <span class="number">4499.00</span>, <span class="string">&quot;http://image.leyou.com/3.jpg&quot;</span>));</span><br><span class="line">    <span class="comment">// 接收对象集合，实现批量新增</span></span><br><span class="line">    itemRepository.saveAll(list);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>再次去页面查询：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;took&quot;</span>: <span class="number">5</span>,</span><br><span class="line">  <span class="attr">&quot;timed_out&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">&quot;_shards&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;successful&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;skipped&quot;</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">&quot;failed&quot;</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;hits&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;total&quot;</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">&quot;max_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;hits&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;item&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;docs&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;2&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;id&quot;</span>: <span class="number">2</span>,</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;坚果手机R1&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;category&quot;</span>: <span class="string">&quot; 手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;brand&quot;</span>: <span class="string">&quot;锤子&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">3699</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;item&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;docs&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;3&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;id&quot;</span>: <span class="number">3</span>,</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;华为META10&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;category&quot;</span>: <span class="string">&quot; 手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;brand&quot;</span>: <span class="string">&quot;华为&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">4499</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;_index&quot;</span>: <span class="string">&quot;item&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_type&quot;</span>: <span class="string">&quot;docs&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_id&quot;</span>: <span class="string">&quot;1&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;_score&quot;</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">&quot;_source&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;id&quot;</span>: <span class="number">1</span>,</span><br><span class="line">          <span class="attr">&quot;title&quot;</span>: <span class="string">&quot;小米手机7&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;category&quot;</span>: <span class="string">&quot; 手机&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;brand&quot;</span>: <span class="string">&quot;小米&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;price&quot;</span>: <span class="number">3499</span>,</span><br><span class="line">          <span class="attr">&quot;images&quot;</span>: <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-4-3-修改文档"><a href="#5-4-3-修改文档" class="headerlink" title="5.4.3.修改文档"></a>5.4.3.修改文档</h3><p>修改和新增是同一个接口，区分的依据就是id，这一点跟我们在页面发起PUT请求是类似的。</p>
<h3 id="5-4-4-基本查询"><a href="#5-4-4-基本查询" class="headerlink" title="5.4.4.基本查询"></a>5.4.4.基本查询</h3><p>ElasticsearchRepository提供了一些基本的查询方法：</p>
<p><img src="assets/1531989728869.png" alt="1531989728869"></p>
<p>我们来试试查询所有：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testFind</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">// 查询全部，并安装价格降序排序</span></span><br><span class="line">    Iterable&lt;Item&gt; items = <span class="keyword">this</span>.itemRepository.findAll(Sort.by(Sort.Direction.DESC, <span class="string">&quot;price&quot;</span>));</span><br><span class="line">    items.forEach(item-&gt; System.out.println(item));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<p><img src="assets/1531990510740.png" alt="1531990510740"></p>
<h3 id="5-4-5-自定义方法"><a href="#5-4-5-自定义方法" class="headerlink" title="5.4.5.自定义方法"></a>5.4.5.自定义方法</h3><p>Spring Data 的另一个强大功能，是根据方法名称自动实现功能。</p>
<p>比如：你的方法名叫做：findByTitle，那么它就知道你是根据title查询，然后自动帮你完成，无需写实现类。</p>
<p>当然，方法名称要符合一定的约定：</p>
<table>
<thead>
<tr>
<th>Keyword</th>
<th>Sample</th>
<th>Elasticsearch Query String</th>
</tr>
</thead>
<tbody><tr>
<td><code>And</code></td>
<td><code>findByNameAndPrice</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : [ &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;, &#123;&quot;field&quot; : &#123;&quot;price&quot; : &quot;?&quot;&#125;&#125; ]&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Or</code></td>
<td><code>findByNameOrPrice</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;should&quot; : [ &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;, &#123;&quot;field&quot; : &#123;&quot;price&quot; : &quot;?&quot;&#125;&#125; ]&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Is</code></td>
<td><code>findByName</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Not</code></td>
<td><code>findByNameNot</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must_not&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Between</code></td>
<td><code>findByPriceBetween</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : ?,&quot;to&quot; : ?,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>LessThanEqual</code></td>
<td><code>findByPriceLessThan</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : null,&quot;to&quot; : ?,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>GreaterThanEqual</code></td>
<td><code>findByPriceGreaterThan</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : ?,&quot;to&quot; : null,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Before</code></td>
<td><code>findByPriceBefore</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : null,&quot;to&quot; : ?,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>After</code></td>
<td><code>findByPriceAfter</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : ?,&quot;to&quot; : null,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Like</code></td>
<td><code>findByNameLike</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &#123;&quot;query&quot; : &quot;?*&quot;,&quot;analyze_wildcard&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>StartingWith</code></td>
<td><code>findByNameStartingWith</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &#123;&quot;query&quot; : &quot;?*&quot;,&quot;analyze_wildcard&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>EndingWith</code></td>
<td><code>findByNameEndingWith</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &#123;&quot;query&quot; : &quot;*?&quot;,&quot;analyze_wildcard&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Contains/Containing</code></td>
<td><code>findByNameContaining</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &#123;&quot;query&quot; : &quot;**?**&quot;,&quot;analyze_wildcard&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>In</code></td>
<td><code>findByNameIn(Collection&lt;String&gt;names)</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;bool&quot; : &#123;&quot;should&quot; : [ &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;, &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125; ]&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>NotIn</code></td>
<td><code>findByNameNotIn(Collection&lt;String&gt;names)</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must_not&quot; : &#123;&quot;bool&quot; : &#123;&quot;should&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Near</code></td>
<td><code>findByStoreNear</code></td>
<td><code>Not Supported Yet !</code></td>
</tr>
<tr>
<td><code>True</code></td>
<td><code>findByAvailableTrue</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;available&quot; : true&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>False</code></td>
<td><code>findByAvailableFalse</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;available&quot; : false&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>OrderBy</code></td>
<td><code>findByAvailableTrueOrderByNameDesc</code></td>
<td><code>&#123;&quot;sort&quot; : [&#123; &quot;name&quot; : &#123;&quot;order&quot; : &quot;desc&quot;&#125; &#125;],&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;available&quot; : true&#125;&#125;&#125;&#125;</code></td>
</tr>
</tbody></table>
<p>例如，我们来按照价格区间查询，定义这样的一个方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ItemRepository</span> <span class="keyword">extends</span> <span class="title">ElasticsearchRepository</span>&lt;<span class="title">Item</span>,<span class="title">Long</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据价格区间查询</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> price1</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> price2</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">List&lt;Item&gt; <span class="title">findByPriceBetween</span><span class="params">(<span class="keyword">double</span> price1, <span class="keyword">double</span> price2)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后添加一些测试数据：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">indexList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    List&lt;Item&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    list.add(<span class="keyword">new</span> Item(<span class="number">1L</span>, <span class="string">&quot;小米手机7&quot;</span>, <span class="string">&quot;手机&quot;</span>, <span class="string">&quot;小米&quot;</span>, <span class="number">3299.00</span>, <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));</span><br><span class="line">    list.add(<span class="keyword">new</span> Item(<span class="number">2L</span>, <span class="string">&quot;坚果手机R1&quot;</span>, <span class="string">&quot;手机&quot;</span>, <span class="string">&quot;锤子&quot;</span>, <span class="number">3699.00</span>, <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));</span><br><span class="line">    list.add(<span class="keyword">new</span> Item(<span class="number">3L</span>, <span class="string">&quot;华为META10&quot;</span>, <span class="string">&quot;手机&quot;</span>, <span class="string">&quot;华为&quot;</span>, <span class="number">4499.00</span>, <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));</span><br><span class="line">    list.add(<span class="keyword">new</span> Item(<span class="number">4L</span>, <span class="string">&quot;小米Mix2S&quot;</span>, <span class="string">&quot;手机&quot;</span>, <span class="string">&quot;小米&quot;</span>, <span class="number">4299.00</span>, <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));</span><br><span class="line">    list.add(<span class="keyword">new</span> Item(<span class="number">5L</span>, <span class="string">&quot;荣耀V10&quot;</span>, <span class="string">&quot;手机&quot;</span>, <span class="string">&quot;华为&quot;</span>, <span class="number">2799.00</span>, <span class="string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));</span><br><span class="line">    <span class="comment">// 接收对象集合，实现批量新增</span></span><br><span class="line">    itemRepository.saveAll(list);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>不需要写实现类，然后我们直接去运行：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">queryByPriceBetween</span><span class="params">()</span></span>&#123;</span><br><span class="line">    List&lt;Item&gt; list = <span class="keyword">this</span>.itemRepository.findByPriceBetween(<span class="number">2000.00</span>, <span class="number">3500.00</span>);</span><br><span class="line">    <span class="keyword">for</span> (Item item : list) &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;item = &quot;</span> + item);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<p><img src="assets/1531993518230.png" alt="1531993518230"></p>
<p>虽然基本查询和自定义方法已经很强大了，但是如果是复杂查询（模糊、通配符、词条查询等）就显得力不从心了。此时，我们只能使用原生查询。</p>
<h2 id="5-5-高级查询"><a href="#5-5-高级查询" class="headerlink" title="5.5.高级查询"></a>5.5.高级查询</h2><h3 id="5-5-1-基本查询"><a href="#5-5-1-基本查询" class="headerlink" title="5.5.1.基本查询"></a>5.5.1.基本查询</h3><p>先看看基本玩法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testQuery</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">// 词条查询</span></span><br><span class="line">    MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery(<span class="string">&quot;title&quot;</span>, <span class="string">&quot;小米&quot;</span>);</span><br><span class="line">    <span class="comment">// 执行查询</span></span><br><span class="line">    Iterable&lt;Item&gt; items = <span class="keyword">this</span>.itemRepository.search(queryBuilder);</span><br><span class="line">    items.forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Repository的search方法需要QueryBuilder参数，elasticSearch为我们提供了一个对象QueryBuilders：</p>
<p> <img src="assets/1532008212626.png" alt="1532008212626"></p>
<p>QueryBuilders提供了大量的静态方法，用于生成各种不同类型的查询对象，例如：词条、模糊、通配符等QueryBuilder对象。</p>
<p>结果：</p>
<p><img src="assets/1532008415257.png" alt="1532008415257"></p>
<p>elasticsearch提供很多可用的查询方式，但是不够灵活。如果想玩过滤或者聚合查询等就很难了。</p>
<h3 id="5-5-2-自定义查询"><a href="#5-5-2-自定义查询" class="headerlink" title="5.5.2.自定义查询"></a>5.5.2.自定义查询</h3><p>先来看最基本的match query：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testNativeQuery</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">// 构建查询条件</span></span><br><span class="line">    NativeSearchQueryBuilder queryBuilder = <span class="keyword">new</span> NativeSearchQueryBuilder();</span><br><span class="line">    <span class="comment">// 添加基本的分词查询</span></span><br><span class="line">    queryBuilder.withQuery(QueryBuilders.matchQuery(<span class="string">&quot;title&quot;</span>, <span class="string">&quot;小米&quot;</span>));</span><br><span class="line">    <span class="comment">// 执行搜索，获取结果</span></span><br><span class="line">    Page&lt;Item&gt; items = <span class="keyword">this</span>.itemRepository.search(queryBuilder.build());</span><br><span class="line">    <span class="comment">// 打印总条数</span></span><br><span class="line">    System.out.println(items.getTotalElements());</span><br><span class="line">    <span class="comment">// 打印总页数</span></span><br><span class="line">    System.out.println(items.getTotalPages());</span><br><span class="line">    items.forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>NativeSearchQueryBuilder：Spring提供的一个查询条件构建器，帮助构建json格式的请求体</p>
<p><code>Page&lt;item&gt;</code>：默认是分页查询，因此返回的是一个分页的结果对象，包含属性：</p>
<ul>
<li>totalElements：总条数</li>
<li>totalPages：总页数</li>
<li>Iterator：迭代器，本身实现了Iterator接口，因此可直接迭代得到当前页的数据</li>
<li>其它属性：</li>
</ul>
<p><img src="assets/1532009679148.png" alt="1532009679148"></p>
<p>结果：<img src="assets/1532009717623.png" alt="1532009717623"></p>
<h3 id="5-5-4-分页查询"><a href="#5-5-4-分页查询" class="headerlink" title="5.5.4.分页查询"></a>5.5.4.分页查询</h3><p>利用<code>NativeSearchQueryBuilder</code>可以方便的实现分页：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testNativeQuery</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">// 构建查询条件</span></span><br><span class="line">    NativeSearchQueryBuilder queryBuilder = <span class="keyword">new</span> NativeSearchQueryBuilder();</span><br><span class="line">    <span class="comment">// 添加基本的分词查询</span></span><br><span class="line">    queryBuilder.withQuery(QueryBuilders.termQuery(<span class="string">&quot;category&quot;</span>, <span class="string">&quot;手机&quot;</span>));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 初始化分页参数</span></span><br><span class="line">    <span class="keyword">int</span> page = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> size = <span class="number">3</span>;</span><br><span class="line">    <span class="comment">// 设置分页参数</span></span><br><span class="line">    queryBuilder.withPageable(PageRequest.of(page, size));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 执行搜索，获取结果</span></span><br><span class="line">    Page&lt;Item&gt; items = <span class="keyword">this</span>.itemRepository.search(queryBuilder.build());</span><br><span class="line">    <span class="comment">// 打印总条数</span></span><br><span class="line">    System.out.println(items.getTotalElements());</span><br><span class="line">    <span class="comment">// 打印总页数</span></span><br><span class="line">    System.out.println(items.getTotalPages());</span><br><span class="line">    <span class="comment">// 每页大小</span></span><br><span class="line">    System.out.println(items.getSize());</span><br><span class="line">    <span class="comment">// 当前页</span></span><br><span class="line">    System.out.println(items.getNumber());</span><br><span class="line">    items.forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<p><img src="assets/1532011610028.png" alt="1532011610028"></p>
<p>可以发现，<strong>Elasticsearch中的分页是从第0页开始</strong>。</p>
<h3 id="5-5-5-排序"><a href="#5-5-5-排序" class="headerlink" title="5.5.5.排序"></a>5.5.5.排序</h3><p>排序也通用通过<code>NativeSearchQueryBuilder</code>完成：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSort</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">// 构建查询条件</span></span><br><span class="line">    NativeSearchQueryBuilder queryBuilder = <span class="keyword">new</span> NativeSearchQueryBuilder();</span><br><span class="line">    <span class="comment">// 添加基本的分词查询</span></span><br><span class="line">    queryBuilder.withQuery(QueryBuilders.termQuery(<span class="string">&quot;category&quot;</span>, <span class="string">&quot;手机&quot;</span>));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 排序</span></span><br><span class="line">    queryBuilder.withSort(SortBuilders.fieldSort(<span class="string">&quot;price&quot;</span>).order(SortOrder.DESC));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 执行搜索，获取结果</span></span><br><span class="line">    Page&lt;Item&gt; items = <span class="keyword">this</span>.itemRepository.search(queryBuilder.build());</span><br><span class="line">    <span class="comment">// 打印总条数</span></span><br><span class="line">    System.out.println(items.getTotalElements());</span><br><span class="line">    items.forEach(System.out::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>结果：</p>
<p><img src="assets/1532012155435.png" alt="1532012155435"></p>
<h2 id="5-6-聚合"><a href="#5-6-聚合" class="headerlink" title="5.6.聚合"></a>5.6.聚合</h2><h3 id="5-6-1-聚合为桶"><a href="#5-6-1-聚合为桶" class="headerlink" title="5.6.1.聚合为桶"></a>5.6.1.聚合为桶</h3><p>桶就是分组，比如这里我们按照品牌brand进行分组：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testAgg</span><span class="params">()</span></span>&#123;</span><br><span class="line">    NativeSearchQueryBuilder queryBuilder = <span class="keyword">new</span> NativeSearchQueryBuilder();</span><br><span class="line">    <span class="comment">// 不查询任何结果</span></span><br><span class="line">    queryBuilder.withSourceFilter(<span class="keyword">new</span> FetchSourceFilter(<span class="keyword">new</span> String[]&#123;<span class="string">&quot;&quot;</span>&#125;, <span class="keyword">null</span>));</span><br><span class="line">    <span class="comment">// 1、添加一个新的聚合，聚合类型为terms，聚合名称为brands，聚合字段为brand</span></span><br><span class="line">    queryBuilder.addAggregation(</span><br><span class="line">        AggregationBuilders.terms(<span class="string">&quot;brands&quot;</span>).field(<span class="string">&quot;brand&quot;</span>));</span><br><span class="line">    <span class="comment">// 2、查询,需要把结果强转为AggregatedPage类型</span></span><br><span class="line">    AggregatedPage&lt;Item&gt; aggPage = (AggregatedPage&lt;Item&gt;) <span class="keyword">this</span>.itemRepository.search(queryBuilder.build());</span><br><span class="line">    <span class="comment">// 3、解析</span></span><br><span class="line">    <span class="comment">// 3.1、从结果中取出名为brands的那个聚合，</span></span><br><span class="line">    <span class="comment">// 因为是利用String类型字段来进行的term聚合，所以结果要强转为StringTerm类型</span></span><br><span class="line">    StringTerms agg = (StringTerms) aggPage.getAggregation(<span class="string">&quot;brands&quot;</span>);</span><br><span class="line">    <span class="comment">// 3.2、获取桶</span></span><br><span class="line">    List&lt;StringTerms.Bucket&gt; buckets = agg.getBuckets();</span><br><span class="line">    <span class="comment">// 3.3、遍历</span></span><br><span class="line">    <span class="keyword">for</span> (StringTerms.Bucket bucket : buckets) &#123;</span><br><span class="line">        <span class="comment">// 3.4、获取桶中的key，即品牌名称</span></span><br><span class="line">        System.out.println(bucket.getKeyAsString());</span><br><span class="line">        <span class="comment">// 3.5、获取桶中的文档数量</span></span><br><span class="line">        System.out.println(bucket.getDocCount());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>显示的结果：</p>
<p><img src="assets/1532012598213.png" alt="1532012598213"></p>
<p>关键API：</p>
<ul>
<li><p><code>AggregationBuilders</code>：聚合的构建工厂类。所有聚合都由这个类来构建，看看他的静态方法：</p>
<p><img src="assets/1526567597724.png" alt="1526567597724"></p>
</li>
<li><p><code>AggregatedPage</code>：聚合查询的结果类。它是<code>Page&lt;T&gt;</code>的子接口：</p>
<p> <img src="assets/1526567748355.png" alt="1526567748355"></p>
<p><code>AggregatedPage</code>在<code>Page</code>功能的基础上，拓展了与聚合相关的功能，它其实就是对聚合结果的一种封装，大家可以对照聚合结果的JSON结构来看。</p>
<p> <img src="assets/1526567889455.png" alt="1526567889455"></p>
<p>而返回的结果都是Aggregation类型对象，不过根据字段类型不同，又有不同的子类表示</p>
<p> <img src="assets/1526568128210.png" alt="1526568128210"></p>
</li>
</ul>
<p>我们看下页面的查询的JSON结果与Java类的对照关系：</p>
<p> <img src="assets/1526571200130.png" alt="1526571200130"></p>
<h3 id="5-6-2-嵌套聚合，求平均值"><a href="#5-6-2-嵌套聚合，求平均值" class="headerlink" title="5.6.2.嵌套聚合，求平均值"></a>5.6.2.嵌套聚合，求平均值</h3><p>代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSubAgg</span><span class="params">()</span></span>&#123;</span><br><span class="line">    NativeSearchQueryBuilder queryBuilder = <span class="keyword">new</span> NativeSearchQueryBuilder();</span><br><span class="line">    <span class="comment">// 不查询任何结果</span></span><br><span class="line">    queryBuilder.withSourceFilter(<span class="keyword">new</span> FetchSourceFilter(<span class="keyword">new</span> String[]&#123;<span class="string">&quot;&quot;</span>&#125;, <span class="keyword">null</span>));</span><br><span class="line">    <span class="comment">// 1、添加一个新的聚合，聚合类型为terms，聚合名称为brands，聚合字段为brand</span></span><br><span class="line">    queryBuilder.addAggregation(</span><br><span class="line">        AggregationBuilders.terms(<span class="string">&quot;brands&quot;</span>).field(<span class="string">&quot;brand&quot;</span>)</span><br><span class="line">        .subAggregation(AggregationBuilders.avg(<span class="string">&quot;priceAvg&quot;</span>).field(<span class="string">&quot;price&quot;</span>)) <span class="comment">// 在品牌聚合桶内进行嵌套聚合，求平均值</span></span><br><span class="line">    );</span><br><span class="line">    <span class="comment">// 2、查询,需要把结果强转为AggregatedPage类型</span></span><br><span class="line">    AggregatedPage&lt;Item&gt; aggPage = (AggregatedPage&lt;Item&gt;) <span class="keyword">this</span>.itemRepository.search(queryBuilder.build());</span><br><span class="line">    <span class="comment">// 3、解析</span></span><br><span class="line">    <span class="comment">// 3.1、从结果中取出名为brands的那个聚合，</span></span><br><span class="line">    <span class="comment">// 因为是利用String类型字段来进行的term聚合，所以结果要强转为StringTerm类型</span></span><br><span class="line">    StringTerms agg = (StringTerms) aggPage.getAggregation(<span class="string">&quot;brands&quot;</span>);</span><br><span class="line">    <span class="comment">// 3.2、获取桶</span></span><br><span class="line">    List&lt;StringTerms.Bucket&gt; buckets = agg.getBuckets();</span><br><span class="line">    <span class="comment">// 3.3、遍历</span></span><br><span class="line">    <span class="keyword">for</span> (StringTerms.Bucket bucket : buckets) &#123;</span><br><span class="line">        <span class="comment">// 3.4、获取桶中的key，即品牌名称  3.5、获取桶中的文档数量</span></span><br><span class="line">        System.out.println(bucket.getKeyAsString() + <span class="string">&quot;，共&quot;</span> + bucket.getDocCount() + <span class="string">&quot;台&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3.6.获取子聚合结果：</span></span><br><span class="line">        InternalAvg avg = (InternalAvg) bucket.getAggregations().asMap().get(<span class="string">&quot;priceAvg&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;平均售价：&quot;</span> + avg.getValue());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<p> <img src="assets/1526572198447.png" alt="1526572198447"></p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">AverageJoe</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://www.averagejoe.top/2018/10/11/leyou/day11-bi-ji/day11-elasticsearch/">http://www.averagejoe.top/2018/10/11/leyou/day11-bi-ji/day11-elasticsearch/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="/about" target="_blank">AverageJoe</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            <span class="chip bg-color">No tag</span>
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'BhOC9gMKAfPsRTjqr679tX7A-gzGzoHsz',
        appKey: 'xb9C1I9k62m6AJvin0UWGhSr',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'en',
        placeholder: 'just go go'
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2018/10/14/leyou/day12-bi-ji/day12-elasticsearch2/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/0.jpg" class="responsive-img" alt="">
                        
                        <span class="card-title"></span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            0.学习目标
独立编写数据导入功能
独立实现基本搜索
独立实现页面分页
独立实现结果排序

1.索引库数据导入昨天我们学习了Elasticsearch的基本应用。今天就学以致用，搭建搜索微服务，实现搜索功能。
1.1.创建搜索服务创建mod
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2018-10-14
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            AverageJoe
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2018/10/08/leyou/day10-bi-ji/day10-shang-pin-guan-li/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/0.jpg" class="responsive-img" alt="">
                        
                        <span class="card-title"></span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            0.学习目标
独立实现商品新增后台
独立实现商品编辑后台
独立搭建前台系统页面

1.商品新增当我们点击新增商品按钮：

就会出现一个弹窗：

里面把商品的数据分为了4部分来填写：

基本信息：主要是一些简单的文本数据，包含了SPU和Spu
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2018-10-08
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            AverageJoe
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2019</span>
            <a href="/about" target="_blank">AverageJoe</a>
            |&nbsp;Powered by&nbsp;<a href="#" target="_blank">AverageJoe</a>
            |&nbsp;Theme&nbsp;<a href="#" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">213.1k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">


    <a href="mailto:1533360044@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1533360044" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1533360044" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/search.xml", 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    
	

	<div id="weather-v2-plugin-simple"></div>
<script>
WIDGET = {
  CONFIG: {
    "modules": "0124",
    "background": 1,
    "tmpColor": "FFFFFF",
    "tmpSize": 16,
    "cityColor": "FFFFFF",
    "citySize": 16,
    "aqiSize": 16,
    "weatherIconSize": 24,
    "alertIconSize": 18,
    "padding": "10px 10px 10px 10px",
    "shadow": "1",
    "language": "auto",
    "borderRadius": 5,
    "fixed": "false",
    "vertical": "middle",
    "horizontal": "center",
    "key": "XZgo8dbNqo"
  }
}
</script>
<script src="https://apip.weatherdt.com/simple/static/js/weather-simple-common.js?v=2.0"></script>
<script src="/js/cursor.js"></script>
</body>

</html>
